我正在尝试在搜索控制器中自定义搜索栏的外观.
设置背景和文本颜色工作正常,但我没有找到一种方法来更改文本字段中的图标的颜色,特别是放大镜和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 …Run Code Online (Sandbox Code Playgroud)