0
点赞
收藏
分享

微信扫一扫

代码创建UISearchDisplayCountroller


在Interface Builder里面有一个控件叫Search Bar and Search Display controller


可以实现如地图搜索框,联系人中的搜索框之类的动态效果,很漂亮


搜索框下面会出现搜索历史,segment切换


但是只发现了在xib文件中的添加方式,没有coding的方式


之所以说不能用coding的方式创建UISearchDisplayController,是因为UISearchDisplayCountroller必须包含在UIViewController中,与之想关联,才能出现动态效果


而且在UIViewController中的属性


1
@property(nonatomic, readonly, retain) UISearchDisplayController *searchDisplayController;
因为此属性是readonly的,所以我们无法修改.
后来无意间看到DocSets的源码 https://github.com/omz/DocSets-for-iOS


发现他也用了Search Bar and Search Display controller控件


但是他没用xib来实现


下面我们一起学习一下


首先我们的VC继承于UIViewController


然后在.h文件中添加属性




1
@property(nonatomic, retain) UISearchDisplayController *searchDisplayController;
去掉 readonly
在.m文件会报错


因为Property 'searchDisplayController' attempting to use instance variable '_searchDisplayController' declared in super class 'UIViewController'


我们加入


@synthesize searchDisplayController;


问题消失,然后我们在viewDidLoad:中创建UISearchDisplayController,添加如下代码




1
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
2
searchBar.delegate = self;
3
[self.view addSubview:searchBar];
4
self.searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
5
self.searchDisplayController.delegate = self;
这样 UISearchDisplayController就简单的创建完成了,其他的数据操作就可以直接看Apple API来操作了

举报

相关推荐

0 条评论