更改UISearchBar中UItextField中图标的颜色

non*_*tic 4 uitextfield uiimage uisearchbar swift

我正在尝试在搜索控制器中自定义搜索栏的外观.

设置背景和文本颜色工作正常,但我没有找到一种方法来更改文本字段中的图标的颜色,特别是放大镜和x按钮.

我发现这个Objective-C代码应该做我想要的但是我很难将它翻译成Swift:

(编辑:跳到工作Swift 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];
Run Code Online (Sandbox Code Playgroud)

我试图翻译成Swift:

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. 
Run Code Online (Sandbox Code Playgroud)

leftView似乎没有图像属性.如何像Objective-C代码那样访问该属性?此外,如果有更好的实现我想要的,请告诉我.

non*_*tic 12

这是解决方案:

// 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
Run Code Online (Sandbox Code Playgroud)