控件就不介绍了,UISearchDisplayController就是把searbar和tableview结合到一块了,直接上代码: .h #import UIKit/UIKit.h@interface ThirdViewController : UIViewControllerUITableViewDelegate,UITableViewDataSource{ NSArray
控件就不介绍了,UISearchDisplayController就是把searbar和tableview结合到一块了,直接上代码:
.h
#import <UIKit/UIKit.h>
@interface ThirdViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>
{
NSArray *_array;
NSArray *_filterData;
UISearchDisplayController *searchDisplayController;
}
@property(nonatomic,strong)UITableView *tableView;
@end
.m
@implementation ThirdViewController
-(void)viewDidLoad
{
[super viewDidLoad];
self.title = @"搜索框";
self.view.backgroundColor = [UIColor redColor];
UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
searchBar.placeholder = @"搜索";
searchBar.delegate = self;
UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
tableView.delegate = self;
tableView.dataSource = self;
tableView.tableFooterView = [[UIView alloc]init];
self.tableView = tableView;
[self.view addSubview:self.tableView];
_array = @[@"11",@"A",@"22aa",@"Aa",@"AAa",@"aaA"];
self.tableView.tableHeaderView = searchBar;
//设置搜索栏提示信息
searchDisplayController.searchBar.prompt = @"搜索提示语";
//不显示searchbar的边框
searchDisplayController.searchBar.searchBarStyle = UISearchBarStyleMinimal;
//显示分段条
searchDisplayController.searchBar.showsScopeBar = YES;
//分段条的集体内容
searchDisplayController.searchBar.scopeButtonTitles = @[@"全部",@"高级",@"初级"];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (self.tableView==tableView) {
return _array.count;
}else
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self contains [cd] %@",searchDisplayController.searchBar.text];
_filterData = [[NSArray alloc]initWithArray:[_array filteredArrayUsingPredicate:predicate]];
return _filterData.count;
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdenfiter = @"CELLS";
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdenfiter];
cell.textLabel.text = _array[indexPath.row];
}
if (self.tableView==tableView) {
cell.textLabel.text = _array[indexPath.row];
}else
{
cell.textLabel.text = _filterData[indexPath.row];
}
return cell;
}
相关的代理方法:
/搜索代理方法,每次改变搜索内容时都会调用
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
NSLog(@"-------%@",searchText);
}
//选择分段时调用
-(void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope
{
NSLog(@"-------%ld",selectedScope);
}
效果如下图:
仅做记录!还有其他的几种样式,大家也可以自己尝试下!不过这中原生的效果用的少,自定义的多!
作者:稻草人11223
【文章原创作者阜宁网站设计公司 http://www.1234xp.com/funing.html 欢迎留下您的宝贵建议】