系統的 UISearchBar 內部有一層直接子視圖,其 frame 等於 searchBar 的 bounds;真正的輸入框與背景則是它的間接子視圖:
UISearchBarBackground:frame 等於 searchBar 的 bounds。UISearchBarTextField:原點固定在 (8.0, 6.0),並不貼齊 bounds。關鍵結論:單純改 searchBar 的 frame 只會改變寬度,不會改變高度。原因有兩個——輸入框高度被寫死為 28,左右邊距固定 8,上下邊距則由「父視圖高度減 28 再除以 2」算出。
做法是自己寫一個子類 IDSearchBar,重新安排子視圖的佈局,並額外開一個 contentInset 屬性用來控制輸入框到父容器的邊距:
contentInset,就沿用系統的預設值。宣告子類:
class IDSearchBar: UISearchBar { }
加入可選的 contentInset,並在值變動時觸發重新佈局:
var contentInset: UIEdgeInsets? {
didSet { self.layoutSubviews() }
}
覆寫 layoutSubviews(),找出內部的 UITextField 並重新設定 frame:
override func layoutSubviews() {
super.layoutSubviews()
// view 是 searchBar 唯一的直接子視圖
for view in self.subviews {
// UISearchBarBackground 與 UISearchBarTextField 是它的間接子視圖
for subview in view.subviews {
if subview.isKindOfClass(UITextField.classForCoder()) {
if let textFieldContentInset = contentInset {
// 使用者有指定邊距:依 contentInset 重新佈局
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 {
// 使用者未指定:套用系統預設邊距
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)
}
}
}
}
}
不設定 contentInset,維持系統外觀:
searchBar.frame = CGRect(x: 80, y: 100, width: 200, height: 40)

設定 contentInset,讓輸入框上下撐滿:
searchBar.frame = CGRect(x: 80, y: 100, width: 200, height: 40) searchBar.contentInset = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)

必須先理解兩件事:UISearchBar 自帶一套預設佈局;而 IDSearchBar 的目標只是改高度,未來也可能出現改寬度的需求。因此設計原則是:
contentInset 作為調整內邊距的單一入口。