1。Options
ShowsSearchResultsButton:勾選該復選框后,將會在搜索文本框的右端顯示一個如“三”形狀的圖標按鈕,用戶可通過淡季該按鈕激發特定的事件。
ShowsBookmarksButton:顯示Cancel按鈕
2.ShowsscopeBar與ScopeTitles
如果勾選ScB,在搜索框下方先是一個分段條。接下來的ST將用于設置各分段的標題。如ST包含三個列表項:aaa,bbb,ccc。則表明搜索框下方先是一個分為三段的分段條。
UISearchBarDelegate協議:
searchBar:textDidChange:文本改變時激發
searchBarBookmarkButtonClicked:點擊搜索條的書簽按鈕
searchBarCancelButtonClocked:
...Search...
searchBarResultsListButtonClicked:點擊搜索條上的 查詢結果按鈕
searchBarLseletedScopeButtonIndexDidChange:當用戶點擊分段條上的分段按鈕時激發
.h---------------------------------------------
@implementationViewController
boolisSearch;
- (void)viewDidLoad {
[superviewDidLoad];
isSearch=NO;
self.tableData=[NSArrayarrayWithObjects:
@"法國",
@"新西蘭",
@"英國",
@"希臘",nil];
self.tableView=[[UITableViewalloc]initWithFrame:CGRectMake(5,55,400,500)style:UITableViewStylePlain];
self.tableView.delegate=self;
self.tableView.dataSource=self;
[self.viewaddSubview:self.tableView];
self.searchBar=[[UISearchBaralloc]initWithFrame:CGRectMake(0,5,418,48)];
self.searchBar.showsCancelButton=YES;
self.searchBar.showsSearchResultsButton=YES;
self.searchBar.showsScopeBar=YES;
self.searchBar.showsBookmarkButton=YES;
self.searchBar.delegate=self;
[self.viewaddSubview:self.searchBar];
// Do any additional setup after loading the view, typically from a nib.
}
-(NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section{
if(isSearch) {
returnself.searchData.count;
}
returnself.tableData.count;
}
-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{
staticNSString* cellId=@"cellId";
UITableViewCell* cell=[tableViewdequeueReusableCellWithIdentifier:cellId];
if(!cell) {
//創建表格行
cell=[[UITableViewCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:cellId];
}
NSIntegerrowNo=indexPath.row;
if(isSearch) {
//使用searchData作為表格顯示的數據
cell.textLabel.text=self.searchData[rowNo];
}else{
//否則使用原始的tableData作為表格顯示的數據
cell.textLabel.text=self.tableData[rowNo];
}
returncell;
}
-(void)searchBarCancelButtonClicked:(UISearchBar*)searchBar{
//取消搜索狀態
isSearch=NO;
[self.tableViewreloadData];
}
//UISearchBarDelegate定義的方法,當搜索文本框內的文本改變時激發該方法
-(void)searchBarSearchButtonClicked:(UISearchBar*)searchBar{
//調用filterBySubstring:方法執行搜索
[selffilterBySubstring:searchBar.text];
//放棄作為第一響應者,關閉鍵盤
[searchBarresignFirstResponder];
}
-(void)filterBySubstring:(NSString*)subStr{
//設置搜索狀態
isSearch=YES;
//定義搜索為此
NSPredicate* pred=[NSPredicatepredicateWithFormat:@"self contains[c] %@",subStr];
//使用為此過濾NSArray
self.searchData=[self.tableDatafilteredArrayUsingPredicate:pred];
//讓表格重新加載數據
[self.tableViewreloadData];
}
- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
10.17.2 使用UISearchDisplayController
下拉列表顯示搜索結果: