UISearchController

weixin_34337265發表於2016-04-03

因為要做一個帶有搜尋欄的頁面,所以找個下search的方法

iOS7以前是UISearchDisplayController

iOS8以後UISearchDisplayController被UISearchController替代,但是考慮對iOS7的適配,還是採用以前的方法。

基本方法:

1.建立searchbar

UISearchBar* searchBar = [[UISearchBaralloc]initWithFrame:CGRectMake(0,0,self.view.frame.size.width,44)];

searchBar.delegate=self;

2.設定tableview的headerview為searchbar

_tableView.tableHeaderView= searchBar;

2.把searchbar給uisearchdisplaycontroller

dc= [[UISearchDisplayControlleralloc]initWithSearchBar:searchBarcontentsController:self];

dc.searchResultsDataSource=self;

dc.searchResultsDelegate=self;

4.更改搜尋背景和搜尋文字背景

for(UIView*subviewinsearchBar.subviews) {

for(UIView* grandSonViewinsubview.subviews){

if([grandSonViewisKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {

grandSonView.alpha=0.0f;

}elseif([grandSonViewisKindOfClass:NSClassFromString(@"UISearchBarTextField")] ){

NSLog(@"Keep textfiedld bkg color");

searchBar.barTintColor= [UIColorblueColor];

grandSonView.backgroundColor= [UIColorredColor];

}else{

//grandSonView.alpha = 0.0f;

grandSonView.backgroundColor= [UIColorredColor];

}

}//for cacheViews

}//subviews

[searchBarsetSearchFieldBackgroundImage:[UIImageimageNamed:@"向量智慧物件"]forState:UIControlStateNormal];

UISearchController的方法:

參考文章