class IDSearchBar: UISearchBar {}增加成员属性contentInset(可选类型),控制UISearchBarTextField距离父控件的边距,监听其值的改变,重新布局searchBar子控件的布局
var contentInset: UIEdgeInsets? {didSet {self.layoutSubviews()}}重写layoutSubviews()布局searchBar的子控件
override func layoutSubviews() {super.layoutSubviews()// view是searchBar中的唯一的直接子控件for view in self.subviews {// UISearchBarBackground与UISearchBarTextField是searchBar的简介子控件for subview in view.subviews {// 找到UISearchBarTextFieldif subview.isKindOfClass(UITextField.classForCoder()) {if let textFieldContentInset = contentInset { // 若contentInset被赋值// 根据contentInset改变UISearchBarTextField的布局subview.frame = CGRect(x: textFieldContentInset.left, y: textFieldContentInset.top, width: self.bounds.width - textFieldContentInset.left - textFieldContentInset.right, height: self.bounds.height - textFieldContentInset.top - textFieldContentInset.bottom)} else { // 若contentSet未被赋值// 设置UISearchBar中UISearchBarTextField的默认边距let top: CGFloat = (self.bounds.height - 28.0) / 2.0let bottom: CGFloat = toplet left: CGFloat = 8.0let right: CGFloat = leftcontentInset = UIEdgeInsets(top: top, left: left, bottom: bottom, right: right)}}}}}三、IDSearchBar使用示例
searchBar.frame = CGRect(x: 80, y: 100, width: 200, height: 40)效果如图
2、设置contentInset
设置searchBar的frame
searchBar.frame = CGRect(x: 80, y: 100, width: 200, height: 40)设置searchBar的contentInset
// 设置contentInsetsearchBar.contentInset = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)效果如图
四、IDSearchBar的设计原则
1、注意