20

UIViewController在情节提要中有一个带有tableview和的设置UISearchDisplayController

我正在尝试使用 self.tableview 中的自定义原型单元(它连接到情节提要中的主 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所以这是原因吗?

4

3 回答 3

60

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

所以不要这样做:

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

而是这样做:

UITableViewCell *cell =
[self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
于 2013-10-05T06:50:56.843 回答
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;
}
于 2013-09-01T16:46:12.043 回答
-1

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

尝试使用此代码

(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomSearchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomSearchCell" forIndexPath:indexPath];
于 2013-09-01T16:25:50.710 回答