ios 5 UISearchDisplayController崩溃

moo*_*oon 24 uitableview uisearchdisplaycontroller ios5 xcode4.2

我在xcode 4.2中使用UISearchDisplayController实现了一个UITableView.UITableView和UISearchDisplayController是在StoryBoard中创建的.我为UITableView设置了Cell Identifier(SampleCell)并像访问它一样

cell = [tableView dequeueReusableCellWithIdentifier:@"SampleCell"];
Run Code Online (Sandbox Code Playgroud)

UItableView工作正常.但是一旦我尝试搜索,应用程序崩溃,出现以下错误.

*** Assertion failure in -[UISearchResultsTableView _createPreparedCellForGlobalRow:withIndexPath:], /SourceCache/UIKit_Sim/UIKit-1912.3/UITableView.m:6072
2011-11-09 22:22:16.058 SampleApp[14362:fb03] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:'
Run Code Online (Sandbox Code Playgroud)

我想我需要为self.searchDisplayController.searchResultsTableView单元格设置单元格标识符.但我不知道怎么做.在此先感谢您的帮助.=)

hus*_*oj2 83

使用[self.tableView dequeue...],而不是[tableView dequeue...].

您尝试出列的单元格tableView与故事板中的主视图控制器相关联,而不是searchDisplayController新创建的tableView单元(没有链接到它的单元标识符).如果您只是发送消息" tableView",那么您的出队消息将转到searchDisplayController'stableView,因为这是传递给cellForRowAtIndexPath:...方法的内容.

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"CellId"];

    // do your thing

    return cell;
}
Run Code Online (Sandbox Code Playgroud)


Ced*_*ick 16

确实要跟踪的硬错误,似乎每次进行搜索时都会创建一个新的tableview.这意味着您的单元格注册必须从ViewDidLoad中取出,因为这只适用于第一次搜索.而是使用以下委托方法进行单元格注册和自定义:

    - (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller
{
    [self.searchDisplayController.searchResultsTableView 
     registerNib:[UINib nibWithNibName:@"YOURCELLNIB" bundle:nil] forCellReuseIdentifier:@"YOURCELLID"];
    self.searchDisplayController.searchResultsTableView.separatorColor = [UIColor clearColor];
}
Run Code Online (Sandbox Code Playgroud)


the*_*jaz 10

(即建议使用self.tableview答案是依赖于另一个表视图.这是干净的解决方案,并且如果搜索控制器用于通过本身甚至可以使用).

您需要在UISearchDisplayController的UITableView上注册单元格.最好的方法是在加载表视图时注册单元格.

UISearchDisplayDelegate具有当表视图加载,通知您的方法 - 就像viewDidLoad中,但对于搜索表视图.

- (void)searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableView
{
    [tableView registerNib:[UINib nibWithNibName:@"MyCellNib" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"MyCellIdentifier"];
}
Run Code Online (Sandbox Code Playgroud)

  • 很有帮助.另请参阅:`registerClass:forCellReuseIdentifier:`如果您的单元格是在代码而不是Interface Builder中定义的. (2认同)