3
我試圖自定義搜索控制器中搜索欄的外觀。更改UISearchBar中UItextField中圖標的顏色
設置背景和文本的顏色工作正常,但我只是沒有找到一種方法來改變文本字段中的圖標的顏色,特別是放大鏡和X按鈕。
我發現這個Objective-C代碼應該做我想做的,但我努力把它翻譯斯威夫特:
(編輯:跳到第一個答案爲工作斯威夫特3溶液。)
UITextField *searchBarTextField = [self.searchDisplayController.searchBar valueForKey:@"_searchField"];
// Magnifying glass icon.
UIImageView *leftImageView = (UIImageView *)searchBarTextField.leftView;
leftImageView.image = [LeftImageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
leftImageView.tintColor = [UIColor whiteColor];
// Clear button
UIButton *clearButton = [searchBarTextField valueForKey:@"_clearButton"];
[clearButton setImage:[clearButton.imageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
clearButton.tintColor = [UIColor whiteColor];
我嘗試翻譯斯威夫特:
let textField = searchController.searchBar.valueForKey("searchField") as! UITextField
// These two work fine.
textField.backgroundColor = UIColor.blackColor()
textField.textColor = UIColor.blackColor()
var glassIcon = textField.leftView
// This would work.
//glassIcon.hidden = true
// This does not have any effect.
//glassIcon?.tintColor = UIColor.whiteColor()
// My attempt to translate, but it gives an error.
glassIcon.image? = UIImage.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
var clearButton = textField.valueForKey("clearButton")!
clearButton.setImage(clearButton.imageWithRenderingMode(.AlwaysTemplate), forState: .Normal)
// This gives the error: "Cannot assign to property: 'clearButton' is immutable
clearButton.tintColor = UIColor.whiteColor()
// Sorry for the weird formatting, it glitches here in the editor.
的leftView似乎沒有圖像屬性。我如何以Objective-C代碼的形式訪問該屬性? 另外,如果有更好的實現我想要的請讓我知道。
謝謝!最後一個簡單的解決方案,工作 – Kashif
嗨,與此代碼,我該如何將它追加到我的搜索欄? –
在您的視圖控制器中實例化一個搜索控制器:'var searchController:UISearchController!'並將其設置在您的viewDidLoad()中,例如:'tableView.tableHeaderView = searchController.searchBar searchController = UISearchController(searchResultsController:nil) searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = false searchController.searchBar.delegate = self searchController.searchBar.sizeToFit() searchController.searchBar.barTintColor = UIColor.white' – nontomatic