2016-02-29 71 views
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代码的形式访问该属性? 另外,如果有更好的实现我想要的请让我知道。

回答

9

这里是解决方案:

// Text field in search bar. 
let textField = searchController.searchBar.value(forKey: "searchField") as! UITextField 

let glassIconView = textField.leftView as! UIImageView 
glassIconView.image = glassIconView.image?.withRenderingMode(.alwaysTemplate) 
glassIconView.tintColor = UIColor.white 

let clearButton = textField.valueForKey("clearButton") as! UIButton 
clearButton.setImage(clearButton.imageView?.image?.withRenderingMode(.alwaysTemplate), for: .normal) 
clearButton.tintColor = UIColor.white 
+0

谢谢!最后一个简单的解决方案,工作 – Kashif

+0

嗨,与此代码,我该如何将它追加到我的搜索栏? –

+0

在您的视图控制器中实例化一个搜索控制器:'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