访问表视图单元格中的某个对象是:通过superview访问单元格是否合法?

时间:2014-01-23 08:46:15

标签: ios objective-c uitableview core-data nsfetchedresultscontroller

我有一个非常可变的表格视图,用户可以通过多种方式一次编辑。添加,删除行并重命名这些单元格内的文本字段中的文本。到目前为止,我已经使用:

访问了单元indexPath
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:textField.tag inSection:0];
    MainCategory *mainCategory = [self.fetchedResultsController objectAtIndexPath:indexPath];

    if(textField.text != mainCategory.name){
        mainCategory.name = textField.text;
    }

    self.activeField = nil;
}

然而,这在重新排序,删除等之后出现问题。现在使用这种方法可以起作用:

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    //NSIndexPath *indexPath = [NSIndexPath indexPathForRow:textField.tag inSection:0];

    // Get the cell in which the textfield is embedded
    id textFieldSuper = textField;
    while (![textFieldSuper isKindOfClass:[UITableViewCell class]]) {
        textFieldSuper = [textFieldSuper superview];
    }

    UITableViewCell *cell = textFieldSuper;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    MainCategory *mainCategory = [self.fetchedResultsController objectAtIndexPath:indexPath];

    if(textField.text != mainCategory.name){
        mainCategory.name = textField.text;
    }

    self.activeField = nil;
}

这是合法的方式吗?

1 个答案:

答案 0 :(得分:1)

它会起作用,但我更喜欢在不需要时避免使用循环。

您可以使用此解决方案:

-(void)textFieldDidEndEditing:(UITextField *)textField
{
        CGPoint pnt = [self.tableView convertPoint:textField.bounds.origin fromView:textField];
        NSIndexPath* indexPath = [self.tableView indexPathForRowAtPoint:pnt];

        MainCategory *mainCategory = [self.fetchedResultsController objectAtIndexPath:indexPath];

        if(textField.text != mainCategory.name){
             mainCategory.name = textField.text;
        }

        self.activeField = nil;
}