要运行示例项目,请克隆仓库,并首先从Example目录运行pod install
。
创建TCTableViewSearchController的子类(或按照您对其他视图控制器的方式呈现)并开始创建你的表格视图。在你的类定义中声明你的类采用协议(TCTableViewSearchControllerDelegate)。你的表格必须由具有属性的实体生成。目前你不能有一个数据源是字符串数组的表格。
然后执行以下步骤
1) 访问正确的项目或项目计数
在您在某个索引路径上操作的对象或需要项目计数的任何UITableViewDataSource或UITableViewDelegate方法中,您需要确定是否要使用主要数据源还是使用filteredResults
数据源。您可以通过检查搜索栏当前是否处于活动状态来实现这一点。
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (!self.searchController.active) {
// return the count of your main data source
} else {
// return the count of the filteredResults property of TCTableViewSearchController
}
}
2) 实现TCTableViewSearchControllerDelegate的必需委托方法。
为了保持简单,只有一个方法需要用来在您的表格中搜索对象数据。您需要提供要搜索的对象,您想要搜索的每个对象的属性(以字符串数组的形式),以及包含这些属性的实体。示例对象用于确定属性类型,它必须是NSString或NSNumber。
- (void)updateSearchResultsForSearchingTableViewController:(TCTableViewSearchController *)searchingTableViewController withCompletion:(TCSearchBlock)completion {
// Provide the properties of the objects in the table that you wish to search. Currently only supports NSStrings and NSNumbers.
NSArray *propertiesArray = [NSArray arrayWithObjects:@"name", @"breed", @"ownerName", @"birthYear", nil]; // These are the properties of the TCDog object represented in string form
completion(self.dogArray, propertiesArray, [TCDog dog]); // The data source, the properties to search, and an example object that will be searched.
}
3)(可选)实现范围栏。
如果需要范围栏,您可能会搜索对象的两个或多个属性。所以如果你需要在必需的委托方法updateSearchResultsForSearchingTableViewController:
中搜索四个属性,那么您需要为范围栏创建五个标题,其中范围标题数组中的第一个标题是“搜索全部”范围。每个额外的范围应该对应于正在搜索的属性的顺序(否则会抛出异常)。
- (NSArray *)scopeBarTitles {
return @[@"All", @"Name", @"Breed", @"Owner", @"Birth Year"];
}
实现此方法将为您创建范围栏,不需要其他操作。
Tim G Carlson,[email protected]
TCTableViewSearchController可在MIT许可证下使用。有关更多信息,请参阅LICENSE文件。