我正在尝试在搜索控制器中自定义搜索栏的外观。
设置背景和文字颜色很好但我没有找到改变文字字段中图标颜色的方法,特别是放大镜和x按钮。
我发现这个Objective-C代码应该做我想要的但是我很难将它翻译成Swift:
(编辑:跳到工作Swift 3解决方案的第一个答案。)
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.
我尝试翻译成Swift:
nested_form_for
leftView似乎没有图像属性。如何像Objective-C代码那样访问该属性? 另外,如果有更好的方法可以实现我的目的,请告诉我。
答案 0 :(得分: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
答案 1 :(得分:0)
这是解决方案:
extension UITextField{
func setLeftIcon(_ icon: UIImage) {
let padding = 8
let size = 20
let outerView = UIView(frame: CGRect(x: 0, y: 0, width: size+padding, height: size) )
let iconView = UIImageView(frame: CGRect(x: padding, y: 0, width: size, height: size))
iconView.image = icon.withRenderingMode(.alwaysTemplate)
iconView.tintColor = UIColor.white
outerView.addSubview(iconView)
leftView = outerView
leftViewMode = .always
}
}