如何修改iOS中UISearchBar清除按钮的颜色/图标?

解决iOS 11中UISearchBar清除按钮改为白色的问题
嗨,我明白你在iOS 11里修改UISearchBar清除按钮颜色时遇到的困扰了!之前尝试的方法失效,大概率是因为iOS 11调整了UISearchBar的内部视图层级,导致你找不到正确的清除按钮实例。下面给你一个可靠的解决方案:
核心思路
在iOS 11及后续版本中,我们可以通过KVC直接获取搜索栏的输入框,再从中拿到清除按钮,然后利用tintColor属性直接修改颜色——这比手动重新绘制图片更简洁高效,也更适配系统逻辑。
修正后的代码
首先修改你的UISearchBar扩展里的setTextFieldClearButtonColor方法,同时优化控件获取逻辑:
extension UISearchBar { // 保留你原有的其他方法,仅修改这个方法 func setTextFieldClearButtonColor(color: UIColor) { // 获取搜索栏的输入框(兼容iOS 11+) guard let textField = self.value(forKey: "searchField") as? UITextField else { return } // 通过KVC获取清除按钮 if let clearButton = textField.value(forKey: "_clearButton") as? UIButton { // 将按钮图片设置为模板模式,这样tintColor才能生效 let tintableImage = clearButton.imageView?.image?.withRenderingMode(.alwaysTemplate) clearButton.setImage(tintableImage, for: .normal) // 设置清除按钮的颜色为目标色(这里是白色) clearButton.tintColor = color } } // 你的其他扩展方法(setTextColor、setPlaceholderTextColor等)保持不变 }
简化初始化逻辑
你在SearchBar类的sharedInit方法里,不需要再层层遍历子视图找按钮,直接调用上面的方法即可:
private func sharedInit() { self.placeholder = "Search" self.setTextColor(color: .white) self.setTextFieldColor(color: UIColor.hexString("549C64")) self.setPlaceholderTextColor(color: .white) self.setSearchImageColor(color: .white) // 直接调用修正后的方法设置清除按钮颜色 self.setTextFieldClearButtonColor(color: .white) // 你的输入框圆角设置逻辑保持不变 if let textfield = self.value(forKey: "searchField") as? UITextField { if let backgroundview = textfield.subviews.first { backgroundview.layer.cornerRadius = 18.0; backgroundview.clipsToBounds = true; } } }
适配iOS 13+的额外提示
如果你的项目需要适配iOS 13及以上版本,可以使用系统公开的searchTextFieldAPI替代KVC,这样更合规:
if #available(iOS 13.0, *) { let textField = self.searchTextField // 后续获取清除按钮的逻辑同上 if let clearButton = textField.value(forKey: "_clearButton") as? UIButton { let tintableImage = clearButton.imageView?.image?.withRenderingMode(.alwaysTemplate) clearButton.setImage(tintableImage, for: .normal) clearButton.tintColor = .white } } else { // iOS 13以下版本用KVC的方式 guard let textField = self.value(forKey: "searchField") as? UITextField else { return } if let clearButton = textField.value(forKey: "_clearButton") as? UIButton { let tintableImage = clearButton.imageView?.image?.withRenderingMode(.alwaysTemplate) clearButton.setImage(tintableImage, for: .normal) clearButton.tintColor = .white } }
这样修改后,你的UISearchBar清除按钮就能成功显示为白色了!
内容的提问来源于stack exchange,提问作者Ilesh Panchal
相关产品推荐
相关产品推荐

