我正在尝试使用我的表格视图实现搜索栏。我的表格视图和搜索栏都使用故事板放置。在我的ViewDidLoad中,我有:
self.searchDisplayController.delegate = self;
self.searchDisplayController.searchResultsDataSource = self;
self.searchDisplayController.searchResultsDelegate = self;
并实施了两种搜索方法:
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *bPredicate = [NSPredicate predicateWithFormat:@"nickname contains[cd] %@",searchText];
NSArray* array = [[NSArray alloc]init];
array = [self.fbfriendList filteredArrayUsingPredicate:bPredicate];
self.searchResult = [NSMutableArray arrayWithArray:array];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
return YES;
}
在我的表格视图中:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = @"addFriend";
cell = [self.tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"FFAddFriendTableViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
if (tableView == self.searchDisplayController.searchResultsTableView)
{
NSLog(@"!!! %@",self.searchResult);
if (cell == nil) {
[self.searchDisplayController.searchResultsTableView registerNib:[UINib nibWithNibName:@"FFAddFriendTableViewCell" bundle:nil] forCellReuseIdentifier:@"addFriend"];
}
else{
NSLog(@"!!! %@",self.searchResult);
// LINE XXXXXXX
cell.nameLabel.text = [[self.searchResult objectAtIndex:indexPath.row] objectForKey:@"nickname"];
}
}
else
{
}
cell.nameLabel.text = [[self.fbfriendList objectAtIndex:indexPath.row] objectForKey:@"nickname"];
return cell;
}
一切都在搜索方面有效。我的NSLogs打印出我的数组中的正确数据。但是,当我想根据NSMutableArray中的数据设置单元格的标签时,它会因错误而崩溃:
-[__NSCFString setText:]: unrecognized selector sent to instance 0x7ff38b5b70e0
我是否遗漏了将搜索栏实施到tableView的任何关键基础?
答案 0 :(得分:2)
在“// LINE XXXXXX”下方的行中,您有
cell.nameLabel = ...
那应该是,
cell.nameLabel.text = ...
答案 1 :(得分:1)
现在将您的表格视图cellrowindex方法更改为此..
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = @"addFriend";
cell = [self.tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"FFAddFriendTableViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
if (tableView == self.searchDisplayController.searchResultsTableView)
{
cell.nameLabel.text = [[self.searchResult objectAtIndex:indexPath.row] objectForKey:@"nickname"];
} else
{
cell.nameLabel.text = [[self.fbfriendList objectAtIndex:indexPath.row] objectForKey:@"nickname"];
}
return cell;
}