UISearchBar 是 iOS 裡最常被拿來做搜尋輸入的元件,但也因為它把外觀細節藏在私有子視圖裡,實作時常遇到「改不了背景色」「不知道鍵盤怎麼收」這類問題。以下把幾個高頻需求整理成可直接套用的片段。
UISearchBar 內部其實由兩個子視圖組成:一個名為 UISearchBarBackground 的背景層,以及一個承載輸入的 UITextField。Interface Builder 並沒有開放直接設定背景色的屬性,因此常見做法是先把背景層移除。
searchBar = [[UISearchBar alloc] init];
searchBar.backgroundColor = [UIColor clearColor];
for (UIView *subview in searchBar.subviews) {
if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
[subview removeFromSuperview];
break;
}
}
另一種更簡短(但更依賴內部結構)的寫法是直接移除第一個子視圖:
[[searchBar.subviews objectAtIndex:0] removeFromSuperview];
需要留意的是,這類操作屬於碰觸私有視圖層結構,iOS 版本更新後可能失效,正式專案建議改用 searchFieldBackgroundImage 之類的公開途徑,或自行以 UIView 組合出搜尋欄外觀。
UISearchBar *m_searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 44, 320, 41)];
m_searchBar.delegate = self;
m_searchBar.barStyle = UIBarStyleBlackTranslucent;
m_searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
m_searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
m_searchBar.placeholder = @"Search";
m_searchBar.keyboardType = UIKeyboardTypeDefault;
UIView *segment = [m_searchBar.subviews objectAtIndex:0];
UIImageView *bgImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"search_bar_bg.png"]];
[segment addSubview:bgImage];
[self.view addSubview:m_searchBar];
讓目前的輸入框放棄第一響應者身分即可:
[searchBar resignFirstResponder];
列表頁最常見的排版是把搜尋欄釘在頂端。做法是建立 TableView 後,把 searchBar 指定給 tableHeaderView,它就會跟著內容一起滾動。
UITableView *myTableView = [[UITableView alloc]
initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width,
self.view.bounds.size.height - 40)
style:UITableViewStylePlain];
myTableView.backgroundColor = [UIColor whiteColor];
myTableView.delegate = self;
myTableView.dataSource = self;
[myTableView setRowHeight:40];
UISearchBar *searchBar = [[UISearchBar alloc]
initWithFrame:CGRectMake(0.0, 0.0, self.view.bounds.size.width, 40)];
searchBar.placeholder = @"Enter Name";
searchBar.delegate = self;
searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
myTableView.tableHeaderView = searchBar;
[self.view addSubview:myTableView];
若希望搜尋欄固定在頂端不隨內容捲動,則不要使用 tableHeaderView,改成把搜尋欄與 TableView 一起放進容器視圖,並讓 TableView 的 frame 從搜尋欄下方開始。
UISearchBar 的客製 mostly 繞著「子視圖」打轉。理解它的組成結構後,背景色、背景圖、鍵盤行為都能對症下藥;但涉及私有子視圖的寫法請務必在升級 iOS 版本後重新驗證。