UISearchBar与UISearchDisplayController
本帖最后由 Sian 于 2015-6-1 14:02 编辑1、一开始呢我是搞不清楚这两个东西有什么关系,或者说UISearchDisplayController我根本就没用过,那么就先来看下UISearchBar的使用效果
2、UISearchBar是个搜索工具条,这个控件的工作原理非常简单,他与UITextField其实有点像,能够监听开始搜索,搜索词变化,搜索结束等一系列状态,并调用代理的相关方法,这些功能UITextField不是也都有吗?只是他是专业的搜索控件,长得好看一点而已!
3、来,看下UISearchBar在TableView中的表现吧,两张图给你看出效果:
4、如何实现呢?
//
//ViewController.m
//Test
//
//Created by 余西安 on 15/6/1.
//Copyright (c) 2015年 Sian. All rights reserved.
//
#import "ViewController.h"
@interface ViewController () <UISearchDisplayDelegate, UISearchBarDelegate>
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSArray *searchArray;
//@property (nonatomic, strong) UISearchDisplayController *searchDisplay;
@end
@implementation ViewController
- (void)viewDidLoad
{
;
self.dataArray = ;
self.searchArray = ;
UISearchBar *searchBar = [ initWithFrame:CGRectMake(0, 0, 0, 44)];
searchBar.delegate = self;
self.tableView.tableHeaderView = searchBar;
// self.searchDisplay = [ initWithSearchBar:searchBar contentsController:self];
// self.searchDisplay.searchResultsDataSource = self;// 搜索结果表格DataSource
// self.searchDisplay.searchResultsDelegate = self; // 搜索结果表格Delegate
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = ;
if (cell == nil){
cell = [ initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"SATestCell"];
}
cell.textLabel.text = self.dataArray;
return cell;
}
#pragma mark - UISearchBar代理方法
/// 搜索框内容发生变化时调用
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
;
for (NSString *string in self.searchArray) {
if (.length || searchText.length == 0){
;
}
}
; // 如果使用UISearchDisplayController这句代码则没必要
}
/// 取消搜索时调用
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
self.dataArray = ;
;
}
@end
5、再来看看UISearchDisplayController是个什么东西,从上图来看,普通的UISearchBar的搜索结果在原有的TableView上展示,当取消时还原原有的所有数据,回到初始状态。
6、UISearchDisplayController则在此基础上做了一点点加工,主要体现在两个方面:第一、搜索结果不在原有的表格上展示,而是在一个新的TableView上显示搜索结果;第二、将搜索页面全屏显示,让用户专注于搜索过程,更简洁美观。
注意:UISearchDisplayController不能单独工作,他需要基于某个UISearchBar!!
7、如果不很清楚,来,看下效果图:
8、代码实现与上面的一致,把注释掉的部分打开即可,事实上就多了那么几行:@property (nonatomic, strong) UISearchDisplayController *searchDisplay;
self.searchDisplay = [ initWithSearchBar:searchBar contentsController:self];
self.searchDisplay.searchResultsDataSource = self;// 搜索结果表格DataSource
self.searchDisplay.searchResultsDelegate = self; // 搜索结果表格Delegate
9、Demo下载
**** Hidden Message ***** 感谢楼主分享 12312345678
页:
[1]