您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 客製 UISearchBar:自由改寫搜尋框的高度

編輯:iOS 開發綜合

一、系統 UISearchBar 的結構

系統的 UISearchBar 內部有一層直接子視圖,其 frame 等於 searchBar 的 bounds;真正的輸入框與背景則是它的間接子視圖:

  • UISearchBarBackground:frame 等於 searchBar 的 bounds。
  • UISearchBarTextField:原點固定在 (8.0, 6.0),並不貼齊 bounds。

關鍵結論:單純改 searchBar 的 frame 只會改變寬度,不會改變高度。原因有兩個——輸入框高度被寫死為 28,左右邊距固定 8,上下邊距則由「父視圖高度減 28 再除以 2」算出。

二、動手改高度

做法是自己寫一個子類 IDSearchBar,重新安排子視圖的佈局,並額外開一個 contentInset 屬性用來控制輸入框到父容器的邊距:

  • 若使用者沒有設定 contentInset,就沿用系統的預設值。
  • 若使用者有設定,就依新值重新計算輸入框的 frame。

宣告子類:

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 作為調整內邊距的單一入口。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved