效果图1
效果图2
其实一般是在第一种情况使用的UISearchController,但是第二种情况这种又懒得去用uisearchbar+uitableview等等去处理,
其实主要是对数据源的合理使用即可
UISearchController通常是用来排查数据的,比如当前的uitableviewcontroller有许多数据,排查之后需要更新显示数据。
首先UISearchController是联通主cntroller与结果controller桥梁
在主controller建立UISearchController对象
@interface UIViewControllerLocation ()
{
UISearchController*searchController0;
}
那么如何联通主controller
CGRectrectBar=CGRectMake(0,0,self.view.frame.size.width,44);
[searchController0.searchBarsetFrame:rectBar];
[self.searchBar addSubview:searchController0.searchBar];
以上代码需要理解的是searchController0.searchBar是一个只读属性,所以不能被assign,
self.searchBar是一个view
/**
* 搜索框*/@PRoperty (weak, nonatomic) IBOutlet UIView*searchBar;
不能够直接使用self.searchBar=searchController0.searchBar;只有tableview.tableHeaderView=searchController0.searchBar才有效果,同样是view不知道为什么
还有比较重要的一点就是,即使模拟器可以正常的显示,但是真机却无法显示searchBar(xcode7+iphone5s+ios8.3)
最终调试得出真机运行时searchController0.searchBar的frame是(0 0,0 0)需要重置frame才可以正常显示
那么如何联通结果controller
@interfaceUIViewControllerLocation ()
{
SearchResult*searchResult;
}
searchResult=[SearchResultnew];
searchController0=[[UISearchController alloc] initWithSearchResultsController:searchResult];
SearchResult是一个uitableviewcontroller
然后是主controller作为了结果controller的数据更新者
searchController0.searchResultsUpdater=self;
需要遵循一个代理
@interfaceUIViewControllerLocation : UIViewController<UISearchResultsUpdating>
然后
//设置活跃性为YES否则需要自行推送结果controllersearchController0.active=YES;
那么主controller如何推送数据到 结果 controller
代理
/**
* 当搜索框开始改变时触发
*
* @param searchController*/-(void)updateSearchResultsForSearchController:(nonnull UISearchController *)searchController
{
searchResult.getResult(@[@70,@71,@72,@73,@74,@75]);
}
结果controller需要处理接受到的数据(使用的block)
#import<UIKit/UIKit.h>#import"NSObjectDataSource.h"/**
* 获取数据
*
* @param idData*/typedefvoid(^GetResult)(ididData);@interfaceSearchResult : UIViewController/**
* 获取数据的block*/@property(nonatomic,copy)GetResult getResult;/**
* 查询数据列表*/@property (weak, nonatomic) IBOutlet UITableView*tabelview;/**
* tableview的datasource代理*/@property(nonatomic,retain)NSObjectDataSource*dataSource;@end
主controller里初始化结果controller的获取数据block
SearchResult*__weak weakSearchResult=searchResult;
searchResult.getResult=^(NSArray*array)
{
weakSearchResult.dataSource.nsArrayModels=array;
[weakSearchResult.tabelview reloadData];
};
在主controller里搜索更新时执行就可以了(只传递最终数据,数据的筛选需要自行处理)