UISearchDisplayController和UITableView原型单元崩溃

问题描述 投票:20回答:4

我在UIViewControllertableview的故事板中设置了UISearchDisplayController

我正在尝试使用self.tableview中的自定义原型单元格(它连接到故事板中的主表视图)。如果self.tableview在加载我的视图时至少返回了1个单元格,它可以正常工作,但是如果self.tableview没有加载单元格(因为没有数据),并且我加载UISearchBar并搜索,则cellForRowAtIndexPath:方法崩溃:

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

    [self configureCell:cell atIndexPath:indexPath];
    return cell;
}

-(void)configureCell:(CustomSearchCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    User *user = [self.fetchedResultsController objectAtIndexPath:indexPath];

    cell.nameLabel.text = user.username;
}

错误:

*** Assertion failure in -[UITableViewRowData rectForRow:inSection:heightCanBeGuessed:]
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'request for rect at invalid index path (<NSIndexPath: 0x9ef3d00> {length = 2, path = 0 - 0})

我的fetchedResultsController似乎在调用上述方法时有数据(1个部分,2行)。它在dequeueReusableCellWithIdentifier线上坠毁。

任何指针/想法?它应该将原型单元从self.tableview出列,但我的猜测是在self.tableview中没有创建,所以这是原因?

iphone ios objective-c uitableview uisearchdisplaycontroller
4个回答
60
投票

除了拥有主表之外,UISearchDisplayController还管理它自己的UITableView(过滤表)。筛选表中的单元格标识符与主表不匹配。您还希望不是通过indexPath获取单元格,因为两个表在行数方面可能相互之间存在很大差异等。

所以不要这样做:

UITableViewCell *cell =
[self.tableView dequeueReusableCellWithIdentifier:CellIdentifier
forIndexPath:indexPath];

而是这样做:

UITableViewCell *cell =
[self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];

7
投票

我通过将原型单元复制到一个新的xib来解决这个问题:

在viewDidLoad中:

[self.searchDisplayController.searchResultsTableView registerNib:[UINib nibWithNibName:@"CustomSearchCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"CustomSearchCell"];

并更新了cellForRowAtIndexPath以使用方法的tableview而不是原始的self.tableview:

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

    [self configureCell:cell atIndexPath:indexPath];
    return cell;
}

0
投票

这是一个古老的话题,但如果有人遇到同样的问题,对我而言,这与在viewDidLoad中拥有这一行有关

self.tableView.estimatedRowHeight = 80;

同时在不同条件下实现具有可变高度的heightForRowAtIndexPath委托方法

if (indexPath.row == 0) {
    return 44 + cellTopSpacing;
} else {
    return 44;
}

删除估计的行高解决了它。


-1
投票

如果在方法celForRowAtIndexPath中使用àUISearchDisplayController,则必须使用tableView参数method而不是控制器的retain指针。

尝试使用此代码

(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomSearchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomSearchCell" forIndexPath:indexPath];
© www.soinside.com 2019 - 2024. All rights reserved.