搜索條(UISearchBar)由一個文本框和幾個按鈕組成,當用戶在文本框輸入部分內容,程序即可按指定的規則進行搜索。
UISearchBar特有的屬性:
Shows Search Results ButtonShows Bookmarks ButtonShows Cancel ButtonUISearchBar控件的不同部分會觸發不同的事件,UISearchBar的委托對象需要實現UISearchBarDelegate協議:
-searchBar:textDidChange:-searchBarBookmarkButtonClicked:-searchBarCancelButtonClicked:-searchBarSearchButtonClicked:-searchBarResultsListButtonClicked:-searchBar:selectedScopeButtonIndexDidChange:@implementation SearchBarViewControllerNSArray* sTableData;NSArray* searchData;bool isSearch;-(void) viewDidLoad{ [super viewDidLoad]; isSearch = NO; sTableData = [NSArray arrayWithObjects:@"無間道",@"賭神",@"縱橫四海",@"重慶森林",@"雷神",@"鋼鐵俠",@"美國隊長",@"復仇者聯盟", nil]; self.searchTable.delegate = self; self.searchTable.dataSource = self; self.searchBar.delegate = self; self.searchTable.tableHeaderView = self.searchBar;}-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ if (isSearch) { return searchData.count; } else{ return sTableData.count; }}-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString* cellId = @"cellId"; UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellId]; if (!cell) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId]; } NSInteger rowNo = indexPath.row; if (isSearch) { cell.textLabel.text = [searchData objectAtIndex:rowNo]; } else{ cell.textLabel.text = [sTableData objectAtIndex:rowNo]; } return cell;}//點擊取消按鈕-(void) searchBarCancelButtonClicked:(UISearchBar *)searchBar{ isSearch = NO; [self.searchTable reloadData];}//當搜索框的文本改變時觸發-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{ [self filterBySubstring:searchText];}-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{ [self filterBySubstring:searchBar.text]; [searchBar resignFirstResponder];}-(void) filterBySubstring:(NSString*)substr{ isSearch = YES; NSPRedicate* pred = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@",substr]; searchData = [sTableData filteredArrayUsingPredicate:pred]; [self.searchTable reloadData];}@end使用UISearchDisplayController,可以直接在搜索條下方顯示搜索列表。
將Search Bar and Search Display Controller拖入界面,除了應用界面上顯示的UISearchBar控件,在Dock面板上還有Search Display Controller控件,默認看不到。選在Search Display Controller控件,在連接檢查器面板可以看到控件的關聯信息。


UISearchDisplayController的Outlet屬性:
這些屬性默認都綁定到當前控制器,因此控制器類接口定義部分實現如下:
@interface SearchDisplayViewController : UIViewController<UITableViewDataSource, UITableViewDelegate,UISearchBarDelegate, UISearchDisplayDelegate>@end控制器的實現代碼和SearBar的實現類似,效果如下:
新聞熱點
疑難解答