继之前发现IOS8摒弃了UIAlert和UIActionSheet,改用新的UIAlertController。今天学检索时发现IOS8之前使用的UISearchDisplayController也被废弃,新添加了UISearchController,并沿用UISearchBar。
UISearchDisplayController例子不多,所以实现了一个留作记录,以共勉。
代码以上一篇第一个工程为例续写。
注:搜索结果控制器类需实现UISearchResultsUpdating协议,搜索栏内容变动时会触发其updateSearchResultsForSearchController:方法。
直接上传代码,代码中有注释。
运行图如下:
@interface ViewController : UITableViewController<UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating>
@property (nonatomic, strong) NSDictionary *countryList;
@property (nonatomic, strong) NSArray *continentList;
@property (nonatomic, strong) NSDictionary *showCountrys;
@property (nonatomic, strong) NSArray *showContinents;
@property (nonatomic, strong) UISearchController *search;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *dataSourcePath = [[NSBundle mainBundle] pathForResource:@"Country" ofType:@"plist"];
self.countryList = [NSDictionary dictionaryWithContentsOfFile:dataSourcePath];
self.continentList = [self.countryList allKeys];
self.showCountrys = self.countryList;
self.showContinents = self.continentList;
// 这里我没有创建另外的UIViewController的搜索栏子类。
self.search = [[UISearchController alloc] initWithSearchResultsController:nil];
// 设置搜索结果控制器,该类实现了UISearchResultsUpdating协议。
self.search.searchResultsUpdater = self;
self.search.searchBar.prompt = @"Please input the country name";
self.search.searchBar.placeholder = @"Search for country ...";
// 需要放在prompt下面,否则初期prompt和textField重叠。
[self.search.searchBar sizeToFit];
// 开始搜索时背景是否显示标识。
self.search.dimsBackgroundDuringPresentation = NO;
// 将其搜索栏设置为tableview的header视图。
self.tableView.tableHeaderView = self.search.searchBar;
}
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController{
NSString * searchText = searchController.searchBar.text;
if ([searchText isEqualToString:@""]) {
self.showCountrys = self.countryList;
self.showContinents = self.continentList;
[self.tableView reloadData];
return;
}
NSMutableArray *showContinentList = [[NSMutableArray alloc] init];
NSMutableDictionary *showCountryDic = [[NSMutableDictionary alloc] init];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains [c] %@", searchText];
for (NSString *continentKey in self.continentList) {
NSArray *countrys = [self.countryList objectForKey:continentKey];
NSMutableArray *showCountryList = [NSMutableArray arrayWithArray:[countrys filteredArrayUsingPredicate:predicate]];
if (nil != showCountryList && [showCountryList count] > 0) {
[showContinentList addObject:continentKey];
[showCountryDic setObject:showCountryList forKey:continentKey];
}
}
self.showCountrys = showCountryDic;
self.showContinents = showContinentList;
// 重新加载数据。
[self.tableView reloadData];
}