效果圖: api
首先在xib裏面拖一個「Searchbar and Search Display」,記得還要放一個tableview在上面 spa
再於.h 文件中的iboutlet 變量 UISearchBar *searchBar 關聯, 如何關聯就很少說了,在xib裏拖拽一個便可。 繼承
下面是我設置searchbar的代碼,放在了viewdidload裏面: it
self.searchBar.delegate = self; io
self.searchBar.autocorrectionType = UITextAutocorrectionTypeNo; table
self.searchBar.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters; 變量
self.searchBar.placeholder = @"搜索"; select
self.searchBar.keyboardType = UIKeyboardTypeDefault; 搜索
[self.searchBar setShowsScopeBar:YES]; queue
[self.searchBar setScopeButtonTitles:[NSArray arrayWithObjects:@"分類",@"價格",@"銷量", nil]];
self.searchBar.selectedScopeButtonIndex = 0;
繼承 UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate。(這裏說一句,我在沒有添加tableview以前,彷佛沒有效果出來的,具體什麼緣由,猜想可能要與tableview一塊兒使用的吧)下面是我實現delegate的具體方法:
-(void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope{
NSLog(@"%d",selectedScope);
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 5;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 44;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"mycell"] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
return cell;
}
僅供參考...