ios8以后的搜索栏

xiaoxiao2021-02-28  70

在重新看以前的入门书时,发现很多API在ios8以后都弃用了。今天是涉及到搜索栏。

在官方文档中可以看到,UISearchDisplayController连同UISearchDisplayDelegate在ios8以后被弃用了,以后用UISearchController替代。

@interface ViewController : UIViewController < UITableViewDelegate , UITableViewDataSource , UISearchBarDelegate , UISearchResultsUpdating >

@property(nonatomic , retain )   NSArray *recipes; // 源数据

@property(nonatomic , retain )   NSMutableArray *searchList; // 用于保存搜索结果的数组

@property(nonatomic , retain )   IBOutlet UITableView *tableview;

@property(nonatomic , retain )   UISearchController *sC;  // 本来叫searchController的,但与后面有个方法里的参数重名了 ,遂改成这个2B名字

@end

-(void) viewDidLoad{

……

sC =  [ [ UISearchController alloc ] initWithSearchResultsController : nil ];

sC.searchResultsUpdater = self;

sC.dimsBackgroundDuringPresentation = NO; // 这两个属性也可改为YES

sC.hidesNavigationBarDuringPresentation = NO;

sC.searchBar.frame = CGRectMake ( sC.searchBar.frame.origin.x , sC.searchBar.frame.origin.y , sC.searchBar.frame.size.width , 44.0) ;

tableview.tableHeaderView = sC.searchBar; // 是用代码添加的搜索栏,在故事板中拖控件拉线拉不上……

}

-numberOfRowsInsection{

if ( sC.active ){ // 新版的不再是对tableview做判断,直接用active属性

return [ searchList count ] ; 

}else {

return [ recipes count ] ;

}

}

-cellForRowAtIndexPath{

……

if ( sC.active ){

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

}else{

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

}

return cell;

}

-prepareForSegue{

if ( [ segue.identifier isEqualToString:@"showRecipeDetail" ] ){

RecipeViewController *destViewController = segue.destinationViewControlelr;

NSIndexPath *indexPath = [ tableview indexPathForSelectedRow ] ;

if( sC.active ){

destViewController.recipeName = [ searchList objectAtIndex:indexPath.row ] ;  // 不然选择的结果会出错

}else{

destViewController.recipeName = [ recipes objectAtIndex:indexPath.row ] ;

}

]

}

-updateSearchResultsForSearchController{

NSString *searchString = [ searchController.searchBar text ] ;

NSPredicate *predicate = [ NSPredicate predicateWithFormat:@"SELF CONTAINS [cd] %@",searchString ] ;

if( searchList != nil ){

[ searchList removeAllObjects ] ;

}

searchList = [ NSMutableArray arrayWithArray: [ recipes filteredArrayUsingPredicate:predicate ] ] ;

[ tableview reloadData ] ;

}

拖控件的暂时没搞清楚怎么写

转载请注明原文地址: https://www.6miu.com/read-749999.html

最新回复(0)