那我们开始吧,下面是Sely写的一个Demo,分享给大家。

新建一个项目, UISearchDisplayController 的 displaysSearchBarInNavigationBar太死板了,达不到想要的效果。
这里进行重新定制, 四个协议, 三个成员变量,第一步OK。

@interface ViewController ()<UISearchBarDelegate,UISearchDisplayDelegate, UITableViewDataSource, UITableViewDelegate>

{

UISearchBar *mySearchBar;

UISearchDisplayController *mySearchDisplayController;

NSMutableArray *suggestResults;

}

@end

//下面我们来初始化我们的三个成员

-(void)initMysearchBarAndMysearchDisPlay

{

mySearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, [UIApplicationsharedApplication].statusBarFrame.size.height, [UIScreen mainScreen].bounds.size.width, 44)];

mySearchBar.delegate = self;

//设置选项

mySearchBar.barTintColor = [UIColor redColor];

mySearchBar.searchBarStyle = UISearchBarStyleDefault;

mySearchBar.translucent = NO; //是否半透明

[mySearchBar setAutocapitalizationType:UITextAutocapitalizationTypeNone];

[mySearchBar sizeToFit];

mySearchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:mySearchBar contentsController:self];

mySearchDisplayController.delegate = self;

mySearchDisplayController.searchResultsDataSource = self;

mySearchDisplayController.searchResultsDelegate = self;

suggestResults = [NSMutableArray arrayWithArray:@[@"此处为推荐词", @"也可以为历史记录"]];

}

//然后呢当然是自定义我们的navigation bar了

-(void)initNavigationBar

{

UIButton *moreButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];

[moreButton setImage:[UIImage imageNamed:@"more"] forState:UIControlStateNormal];

[moreButton addTarget:self action:@selector(handleMore:) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *moreItem = [[UIBarButtonItem alloc] initWithCustomView:moreButton];

UIButton *searchButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];

[searchButton setImage:[UIImage imageNamed:@"info_search"] forState:UIControlStateNormal];

[searchButton addTarget:self action:@selector(startSearch:) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *searchItem = [[UIBarButtonItem alloc] initWithCustomView:searchButton];

self.navigationItem.rightBarButtonItems = @[moreItem, searchItem];

}

//好了, 开始加载界面了

- (void)viewDidLoad

{

[super viewDidLoad];

[self initNavigationBar];

[self initMysearchBarAndMysearchDisPlay];

}

//实现我们的点击事件

#pragma mark - handle button click

-(void) startSearch:(id)sender

{

[self.navigationController.view addSubview:mySearchBar];

[mySearchBar becomeFirstResponder];

}

-(void) handleMore:(id)sender

{}

//实现我们的table view 的协议,判断当我们开始搜索时,转到自己实现的一个searchDisplayController方法里,这样代码看起来是不是很简洁?

#pragma mark - UITableViewDataSource & UITableViewDelegate

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

if (tableView == mySearchDisplayController.searchResultsTableView)

{

return [self numberOfRowsWithSearchResultTableView];

}

return 0;

}

-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

if (tableView == mySearchDisplayController.searchResultsTableView)

{

return [self searchTableView:mySearchDisplayController.searchResultsTableView cellForRowAtIndexPath:indexPath];

}

else

{

static NSString *cellID = @"search_cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

if (cell == nil)

{

cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];

}

return cell;

}

}

//这里专门写UISearchDisplayController 中 searchResultsTableView 的 data source 和 delegate

#pragma mark - UISearchDisplayController   <UITableViewDataSource> dataSource

-(NSInteger)numberOfRowsWithSearchResultTableView

{

return suggestResults.count + 1;

}

-(UITableViewCell*)searchTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

static NSString *suggestId = @"suggestCell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:suggestId];

if (cell == nil)

{

cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:suggestId];

cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

}

if (indexPath.row == suggestResults.count)

{

cell.textLabel.text = [NSLocalizedString(@"Search: ", @"查找: ") stringByAppendingString:mySearchBar.text];

}

else

{

cell.textLabel.text = [suggestResults objectAtIndex:indexPath.row];

}

return cell;

}

#pragma mark - UISearchDisplayController <UITableViewDelegate> delegate

-(void) searchTableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

NSString *keyword = nil;

if (indexPath.row == suggestResults.count)

{

keyword = mySearchBar.text;

}

else

{

keyword = [suggestResults objectAtIndex:indexPath.row];

}

[mySearchBar resignFirstResponder];

}

//开始我们的search bar delegate,输入搜索内容, 因为是Demo ,所以我并没有搜索结果,这个大家根据需求自己实现吧

#pragma mark - UISearchBarDelegate

-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar

{

return YES;

}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar

{

}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText

{

[mySearchDisplayController.searchResultsTableView reloadData];

}

//最后的环节了, 这个地方的逻辑就会千变万化了

#pragma mark - UISearchDisplayDelegate

- (void) searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller NS_DEPRECATED_IOS(3_0,8_0)

{

//开始搜索事件,设置searchResultsTableView的contentInset,否则位置会错误

mySearchDisplayController.searchResultsTableView.contentInset = UIEdgeInsetsMake(mySearchBar.frame.size.height, 0, 0, 0);

}

- (void)searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableViewNS_DEPRECATED_IOS(3_0,8_0)

{

//加载searchResultsTableView完毕

}

- (void) searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller NS_DEPRECATED_IOS(3_0,8_0)

{

//结束搜索事件,移除mySearchBar

[mySearchBar removeFromSuperview];

}

// return YES to reload table. called when search string/option changes. convenience methods on top UISearchBar delegate methods

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString*)searchString NS_DEPRECATED_IOS(3_0,8_0)

{

//是否需要刷新searchResultsTableView

if(@"符合条件")

{

return YES;

}

return NO;

}

就到这里结束,是不是很容易? 这是第一次发布,如果做的不好,请大神指正,如果文笔不好(估计是肯定的),也请多指教,最后希望能多多帮助到大家。

源码地址

Sely 原创

如何在UINavigationBar上添加UISearchBar以及UISearchDisplayController的使用 --OC --iOS的更多相关文章

  1. 如何在MyEclipse上添加更换JRE

    如何在myeclipse上添加更换JRE 由于兼容性的问题,有些WEB项目会依赖jdk的版本.如果需要更换jdk,那么,知道如何更换JRE的方法很有必要. 一种在myeclipse上添加和更换JRE的 ...

  2. 如何在TableView上添加悬浮按钮

    如果直接在TableVIewController上贴Button的话会导致这个会随之滚动,下面解决在TableView上实现位置固定悬浮按钮的两种方法: 1.在view上贴tableView,然后将悬 ...

  3. 如何在UILable上添加点击事件?

    最近开始学习iOS开发,今天上来写第一个iOS笔记 昨天碰到一个需求,在UILable上添加点击事件,网上找了写资料,有人建议用透明的UIButton覆盖,有人建议写一个集成自UILable的类,扩展 ...

  4. 如何在IDEA上 添加GIT和maven、mybatis插件

    IDEA工具上,添加GIT和maven.mybatis插件,相对比较简单: 首先下载GIT.maven.mybatis. 先添加GIT插件: 首先在IDEA找到file中找到setting,然后搜索g ...

  5. 如何在UITableViewController上添加一个固定的视图

    最近在使用UITableViewController,想在上面添加一个固定的视图,不随ScrollView滑动而移动.最后找到2种解决办法,一种是计算TableView的偏移,调整视图的位置,不断更新 ...

  6. 代码规范:idea上添加阿里巴巴Java开发插件

    在一个项目中,不可缺少的是书写代码的规范,没有好的代码规范约束,大家各写各的,十分不利于代码的维护与修改.     首先来看看如何在idea上添加这个插件: 直接上图 点击右边的蓝色按钮就可以安装了, ...

  7. 如何在Linux上通过grub添加内核参数

    转自Linux中国 我们可以在linux内核启动时为其提供各种各样的参数.这些参数可以自定义内核默认的行为,或者通知内核关于硬件的配置信息.内核参数应在内核启动时通过引导装载程序,如GRUB或LILO ...

  8. 如何在JDBC Connection Configuration配置组件上添加控件

    如何在JDBC Connection Configuration配置组件上添加控件 最近项目刚上线,闲来无事又把Jmeter的源码拿出来研究研究,最初的目的是想扒一扒Jmeter里数据库处理的逻辑是怎 ...

  9. echart--如何在折线图上添加矩形背景(可以借用bar柱状图的实现效果)

    当鼠标滑过,如何在折线图上添加矩形背景图呢? 具体如下: 上面的dataShadow的来源

随机推荐

  1. 亦步亦趋在CentOS 6.4下安装Oracle 11gR2(x64)

    安装前须知: 内存(RAM)的最小要求是 1GB,建议 2GB 及以上. 虚拟内存 swap 建议:内存为 1GB~2GB 时建议swap大小为内存大小的 1.5 倍:内存为 2GB~16GB 时建议 ...

  2. ADO.NET 快速入门(七):使用数据库事务

    数据库事务用于控制数据提交到数据库.例如,在标准的账户程序,账户的借贷必须同时完成.由于电脑偶尔发生故障(电力中断.网络中断,等等),可能有些记录被更新或者添加,但是另外一些没有.为了避免这些情况,可 ...

  3. Java中throws和throw的区别讲解

    当然,你需要明白异常在Java中式以一个对象来看待.并且所有系统定义的编译和运行异常都可以由系统自动抛出,称为标准异常,但是一般情况下Java 强烈地要求应用程序进行完整的异常处理,给用户友好的提示, ...

  4. MFC Windows程序设计源代码免费下载

    本人近期在网上找到了<MFC Windows程序设计>第二版的书内程序的源代码,特意上传CSDN上面,供学习MFC的程序猿们免费下载. 源代码下载: http://download.csd ...

  5. swift3.0 中NSNotification 的使用

    swift3.0 有很大变化,其中之一就是NSNotification使用跟原来不一样,以前NSNotification name是String:3.0中定义了一个类型NSNotification.n ...

  6. inline(内联元素)和block(块级元素) 的区别

    块级元素,默认是独自占据一行的.比如是<p>.<h1>.<h2>.<h3>.<h4>.<h5>.<h6>.<u ...

  7. [Javascript,JSON] JQuery处理json与ajax返回JSON实例

    转自:http://www.php100.com/html/program/jquery/2013/0905/5912.html [导读] json数据是一种经型的实时数据交互的数据存储方法,使用到最 ...

  8. android-partition分析

    转载请注明来源:cuixiaolei的技术博客 这里讲下android的分区.具体的使用在另一片文章中介绍,这里只是把它拿出来介绍. android的存储分为两种 一种叫做RAM,如emmc标准的dd ...

  9. android源码编译过程

    1.下载好android源码包. 2.装好vm,ubuntu(如果能在实体机装linux更好). 3.安装所需要的deb包 在终端执行如下命令: sudo apt-get install flex b ...

  10. MapReduce的手机流量统计的案例

    程序:(另外一个关于单词计数的总结:http://www.cnblogs.com/DreamDrive/p/5492572.html) import java.io.IOException; impo ...