您的位置:首页 > 产品设计 > UI/UE

UISearchBar

2016-03-18 21:59 411 查看
最近用到了UISearchBar和UISearchDisplayController,一般大体的布局是:

上面是一个navigationController,接下来一个searchBar,下面是tableView

searchBar这个控件就用来搜索tableView上的数据

displayController = [[UISearchDisplayController alloc] initWithSearchBar:searchBarcontentsController:self];

UISearchDisplayController这个控件很强大,它初始化是基于searchBar的,里面有些效果很不错,apple都封装好了,并且可以很好的支持实时搜索,即我们只需要将搜索出来的数据重新赋给array(这个array用来存储tableView数据),不需要reloadData,就会自动出来

其实reloadData也没用,为什么呢?因为搜索出来的结果显示在tableView上,该tableView并不是当前布局的那个tableView,而是另外一个,我猜测应该是UISearchDisplayController里面自带的,所以不要混淆了

特别是在tableView代理方法里,有时候需要判断代理方法传入的tableView是否为当前布局的tableView,因为也有可能是UISearchDisplayController里自带的,它们同样会触发代理方法

当点击searchBar时,它会自动上移并且遮住navigationController

经过测试,如果上面是navigationBar,则searchBar不会移动,但如果是UINavigationController自带过来的,则会上移覆盖

往往有的时候都是UINavigationController自带过来的,如果使用UISearchDisplayController,searchBar就会自动覆盖,这个情况我试了很多次,包括新创建了一个navigationBar盖在上面,但效果依然不好,对于这种情况,基于我目前的技术,只能舍弃UISearchDisplayController,单纯的用UISearchBar了,虽然效果差了一些,但需要实现的功能照样可以,比如实时搜索,除了重新赋值给array外,额外的操作就是需要reloadData了。

有时候点击searchBar时,右侧可能没有出现‘cancel/取消’按钮,这时需要调用下面的方法

- (void)setShowsCancelButton:(BOOL)showsCancelButton animated:(BOOL)animated

相信看方法名字就知道是做什么的了

手动创建这样的一个UISearchDispalyController的方法是:

displayController = [[UISearchDisplayController alloc] initWithSearchBar:searchBarcontentsController:self];

displayController.delegate = self;

displayController.searchResultsDelegate = self;

displayController.searchResultsDataSource = self;

UISearchDispalyController自带了一个选择的按钮,showsScopeBar属性,首先你得定义一个数组,就是按钮的标题

self.searchDisplayController.searchBar.scopeButtonTitles =
[NSArray arrayWithObjects:@"All",@"Iphone",@"Ipad",@"Mac", nil];

self.searchDisplayController.searchBar.showsScopeBar = NO;

self.searchDisplayController.searchBar.selectedScopeButtonIndex = 0;

self.searchDisplayController.searchBar.placeholder = @"请输入字母搜索";

[self.mytableView addSubview:searchBar];//tableView
上加的searchBar
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: