0

我一直在努力解决这个问题,但我似乎找不到一种优雅的方式。我试图在创建单元格后注入代码以使UITextView我的自定义成为第一响应者。UITableViewCell

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
       atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
      newIndexPath:(NSIndexPath *)newIndexPath
{
    UITableView *tableView = self.tableView;

    switch(type) {
        case NSFetchedResultsChangeInsert:
            // store some of the cell information
            _newlyCreatedCell = @{@"path": newIndexPath, @"age":[NSDate date],@"cell":(CustomCell*)[tableView cellForRowAtIndexPath:newIndexPath]};

           [[(CustomCell*)[tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:newIndexPath.row-1 inSection:0]] textLabel] becomeFirstResponder];

            // highlight cell
            [tableView selectRowAtIndexPath:newIndexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
            [tableView deselectRowAtIndexPath:newIndexPath animated:YES];

            [tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];

            break;
}

我得到了这个粗略的代码,但它似乎不是最好的方法或有效的方法。我有一个粗略而错误的想法,将新创建的单元格的信息存储在NSDictionary. 很坏。无论如何,然后我开始摆弄更改newIndexPath值,因为它没有返回NSIndexPath新创建的单元格(可能写在某处的Apple文档中......)。所以我将值设置为[NSIndexPath indexPathForRow:newIndexPath.row-1 inSection:0],当然期望它会返回正确的值。但这又回来了(null)。没啥事儿。

有人知道在创建新单元格时执行一堆代码的更好且可能更简单的方法吗?

4

2 回答 2

1

我从来没有自己尝试过,但是UITableViewDelegate方法

tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

在这里可能会有所帮助。如文档中所述:

表格视图在使用单元格绘制一行之前将此消息发送给其委托人,从而允许委托人在单元格对象显示之前对其进行自定义。此方法使委托有机会覆盖先前由表视图设置的基于状态的属性,例如选择和背景颜色。

如果一次插入多个单元格,可能会出现问题。但是您使用 NSFetchedResultsController,它对用于填充单元格的数据进行排序,所以也许您可以找出哪个单元格是“最后一个”。

于 2013-11-07T15:01:00.510 回答
0

我对您为什么要在创建单元格信息之前尝试访问它感到困惑。您不应该在创建单元格的文本标签后尝试使其成为第一响应者吗?就像是:

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
   atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
  newIndexPath:(NSIndexPath *)newIndexPath {

UITableView *tableView = self.tableView;

switch(type) {

    case NSFetchedResultsChangeInsert:
        [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]
                         withRowAnimation:UITableViewRowAnimationFade];

        //Then do
       [[(CustomCell*)[tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:newIndexPath.row inSection:0]] textLabel] becomeFirstResponder];

        break;
}
于 2013-11-07T14:55:00.830 回答