我正在尝试在搜索控制器中自定义搜索栏的外观.
设置背景和文本颜色工作正常但我没有找到一种方法来更改文本字段中的图标的颜色,特别是放大镜和x按钮.
我发现这个Objective-C代码应该做我想要的但是我很难将它翻译成Swift:
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];
我试图翻译成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.
leftView似乎没有图像属性.如何像Objective-C代码那样访问该属性?
此外,如果有更好的实现我想要的,请告诉我.
解决方法
这是解决方案:
// 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。