在Interface Builder里面有一个控件叫Search Bar and Search Display controller git
能够实现如地图搜索框,联系人中的搜索框之类的动态效果,很漂亮 github
搜索框下面会出现搜索历史,segment切换 学习
可是只发现了在xib文件中的添加方式,没有coding的方式 ui
之因此说不能用coding的方式建立UISearchDisplayController,是由于UISearchDisplayCountroller必须包含在UIViewController中,与之想关联,才能出现动态效果 atom
并且在UIViewController中的属性 spa
@property(nonatomic, readonly, retain) UISearchDisplayController *searchDisplayController;由于此属性是readonly的,因此咱们没法修改.
后来无心间看到DocSets的源码 https://github.com/omz/DocSets-for-iOS code
发现他也用了Search Bar and Search Display controller控件 继承
可是他没用xib来实现 get
下面咱们一块儿学习一下 源码
首先咱们的VC继承于UIViewController
而后在.h文件中添加属性
@property(nonatomic, retain) UISearchDisplayController *searchDisplayController;去掉 readonly
在.m文件会报错
由于Property 'searchDisplayController' attempting to use instance variable '_searchDisplayController' declared in super class 'UIViewController'
咱们加入
@synthesize searchDisplayController;
问题消失,而后咱们在viewDidLoad:中建立UISearchDisplayController,添加以下代码
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)]; searchBar.delegate = self; [self.view addSubview:searchBar]; self.searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self]; self.searchDisplayController.delegate = self;这样 UISearchDisplayController就简单的建立完成了,其余的数据操做就能够直接看Apple API来操做了