首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS 移除 UISearchBar 預設邊框與背景圖片實作

     編輯:程式設計綜合問答

UISearchBar 預設包含圓角背景、邊框、書籤/取消按鈕區域等視覺元素,若需「無邊框、透明背景、純輸入框」效果,需遍歷子視圖移除 UISearchBarBackground 類別的視圖,並調整 searchFieldBackgroundPositionAdjustment。

核心代碼(Objective-C)


for (UIView *subview in searchBar.subviews) {
    for (UIView *subSubView in subview.subviews) {
        if ([subSubView isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
            [subSubView removeFromSuperview];
            break;
        }
    }
}

// 進一步調整輸入框位置(可選)
searchBar.searchFieldBackgroundPositionAdjustment = UIOffsetMake(0, 0);

Swift 版本


func removeSearchBarBackground(_ searchBar: UISearchBar) {
    // iOS 13+ 直接存取 searchTextField
    if #available(iOS 13.0, *) {
        searchBar.searchTextField.backgroundColor = .clear
        searchBar.searchTextField.borderStyle = .none
        return
    }
    
    // iOS 12 及以下:遍歷子視圖
    for subview in searchBar.subviews {
        for subSubView in subview.subviews {
            if String(describing: type(of: subSubView)).contains("UISearchBarBackground") {
                subSubView.removeFromSuperview()
                break
            }
        }
    }
}

現代最佳實踐:iOS 13+ 直接配置 searchTextField


let searchBar = UISearchBar()
searchBar.searchTextField.backgroundColor = .clear
searchBar.searchTextField.borderStyle = .none
searchBar.searchTextField.textColor = .label
searchBar.searchTextField.font = .systemFont(ofSize: 16)
searchBar.searchTextField.leftView?.tintColor = .secondaryLabel // 放大鏡顏色
searchBar.searchTextField.clearButtonMode = .whileEditing

外觀配置速查表

需求屬性/方法備註
移除背景/邊框遍歷移除 UISearchBarBackground / iOS 13+ searchTextField.backgroundColor = .clear核心需求
隱藏取消按鈕searchBar.showsCancelButton = false預設 false
隱藏書籤/搜尋結果按鈕searchBar.showsBookmarkButton = false / showsSearchResultsButton = false
自訂佔位文字searchBar.placeholder = "搜尋..."
自訂輸入框圓角searchBar.searchTextField.layer.cornerRadius = 8 (iOS 13+)需 clipsToBounds = true

注意事項

  • 私有類別名稱(UISearchBarBackground)在 iOS 版本間可能變更,建議改用 iOS 13+ 公開 API。
  • 移除背景後,搜尋框可能失去點擊區域 → 確保 searchTextField 有足夠 contentInset 或外層容器處理觸控。
  • App Store 審核不禁止使用私有 API 移除視覺元素,但未來版本可能失效,需測試相容性。

掌握 UISearchBar 內部結構與現代 API,能打造完美融入設計系統的搜尋介面。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved