我已將UISearchDisplayController與搜索欄一起連接到我的應用程序中。我已將其初始化爲:爲什麼開始搜索時我的搜索表視圖不顯示?
self.filteredObjectArray = [NSMutableArray arrayWithCapacity:[self.objectArray count]];
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 43)];
searchBar.delegate = self;
[self.view addSubview:searchBar];
UISearchDisplayController *searchDisplay = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
searchDisplay.delegate = self;
searchDisplay.searchResultsTableView.delegate = self;
searchDisplay.searchResultsDataSource = self;
searchDisplay.searchResultsDelegate = self;
這是我在其他示例中看到的方式。我也實施了相應的委託方法,如下所示的重要filterContentForSearchText和shouldReload *方法:
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
[self.filteredObjectArray removeAllObjects]; // First clear the filtered array.
for (XRay *xray in objectArray) {
NSString *combinedLabel = [self combinedLabel:xray];
if ([combinedLabel rangeOfString:searchText options:(NSCaseInsensitiveSearch)].location != NSNotFound) {
[self.filteredObjectArray addObject:xray];
}
}
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString scope:
[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
return YES;
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption
{
[self filterContentForSearchText:self.searchDisplayController.searchBar.text scope:
[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
return YES;
}
然而,當我給搜索文本框中焦點或輸入任何字符,我的搜索是行不通的。您還會注意到灰色的視圖不會顯示在我的常規表格視圖中。
編輯 的cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"XraySearchChoice";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
XRay *xray = nil;
if (tableView == self.searchDisplayController.searchResultsTableView) {
xray = [self.filteredObjectArray objectAtIndex:indexPath.row];
} else {
xray = [self.objectArray objectAtIndex:indexPath.row];
}
cell.textLabel.text = [self combinedLabel:xray];
return cell;
}
看起來你正在使用ARC。在您將其聲明爲屬性之前,它早於您的預期被釋放。您可以將其分配給_searchDisplayController實例變量,或者像您所做的那樣聲明一個屬性。不要忘記在你的'viewDidUnload'中將它設置爲nil。 – 2012-04-25 13:02:24