UISearchBar的扩展使用

1. 设置背景颜色

let searchBar = UISearchBar.init()
searchBar.barTintColor = UIColor.white

2. 去除上下黑线


let bgView = UIView.init(frame: searchBar.bounds)
bgView.backgroundColor = UIColor.white
searchBar.insertSubview(bgView, at: 1)

3. 设置背景颜色的同时去掉上下黑线

对UISearchBar进行扩展

var wh_backgroundColor: UIColor? {
        
    get { return self.barTintColor }
        
    set {
        self.barTintColor = newValue
        
        let bgView = UIView.init(frame: self.bounds)
        bgView.backgroundColor = newValue
        self.insertSubview(bgView, at: 1)
    }
}

使用时直接给UISearchBar的wh_backgroundColor属性赋值需要设置的颜色即可

4. 设置搜索框的背景颜色

UISearchBar的输入框是私有的,所以需要自己去获取,在此对UISearchBar进行扩展,这种方式尽量在对UISearchBar的所有设置完成之后再调用,否则可能会出现nil,那么就会设置失败

  1. 获取searchBar中编辑框的视图
var wh_searchBarTextField: UITextField? {
        
        let sub = self.subviews.first?.subviews ?? []
        
        for view in sub {
            if let textField = view as? UITextField {
                return textField
            }
        }
        return nil
    }
  1. 给输入框进行背景颜色设置
searchBar.wh_searchBarTextField?.backgroundColor = UIColor.white
  1. 获取到了输入框,还可以对其进行其余的设置
原文地址:https://www.cnblogs.com/zhanbaocheng/p/7590280.html