我在 Storyboard 中使用UIViewControllertableview设置了UISearchDisplayController

我正在尝试使用self.tableview(连接到Storyboard中的主tableview)的自定义原型(prototype)单元。如果在加载 View 时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中取出原型(prototype)单元,但是我猜self.tableview中没有创建任何原型(prototype)单元,这是原因吗?

最佳答案

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

因此,不要这样做:

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

而是这样做:
UITableViewCell *cell =
[self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];

关于iphone - UISearchDisplayController和UITableView原型(prototype)单元崩溃,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18560300/

10-11 14:33
查看更多