UISearchBar 預設包含圓角背景、邊框、書籤/取消按鈕區域等視覺元素,若需「無邊框、透明背景、純輸入框」效果,需遍歷子視圖移除 UISearchBarBackground 類別的視圖,並調整 searchFieldBackgroundPositionAdjustment。
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);
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
}
}
}
}
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 或外層容器處理觸控。掌握 UISearchBar 內部結構與現代 API,能打造完美融入設計系統的搜尋介面。