UISearchBar改变搜索框的高度
参考: http://www.cnblogs.com/theDesertIslandOutOfTheWorld/p/5015653.html
为什么改变不了系统searchBar的高度?
原因分析:
改变searchBar的frame只会影响其中搜索框的宽度,不会影响其高度,原因如下:
- 系统searchBar中的UISearchBarTextField的高度默认固定为28
- 左右边距固定为8,上下边距是父控件view的高度减去28除以2
解决思路
1. 重写UISearchBar的子类(IDSearchBar),重新布局UISearchBar子控件的布局
2. 增加成员属性contentInset,控制UISearchBarTextField距离父控件的边距
2.1 若用户没有设置contentInset,则计算出默认的contentInset
2.2 若用户设置了contentInset,则根据最新的contentInset布局UISearchBarTextField
class IDSearchBar: UISearchBar {
}
var contentInset: UIEdgeInsets? {
didSet {
self.layoutSubviews()
}
}
override func layoutSubviews() {
super.layoutSubviews()
// view是searchBar中的唯一的直接子控件
for view in self.subviews {
// UISearchBarBackground与UISearchBarTextField是searchBar的简介子控件
for subview in view.subviews {
// 找到UISearchBarTextField
if 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.0
let bottom: CGFloat = top
let left: CGFloat = 8.0
let right: CGFloat = left
contentInset = UIEdgeInsets(top: top, left: left, bottom: bottom, right: right)
}
}
}
}
}
image.png
网友评论