在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來操做了