简体   繁体   English

在表格视图中访问我的自定义单元格

[英]accessing my custom cell in a tableview

Right now I have a tableview that is built like this: 现在,我有一个像这样构建的表视图:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"PhotoCell";
    PhotoSummaryCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    // Configure the cell...

    NSString *photoCaption = [[[self.form valueForKey:@"photos"] objectAtIndex:indexPath.row] objectForKey:@"caption" ];

    cell.textfieldCaption.text = photoCaption;
    cell.textfieldCaption.tag=indexPath.row;

    return cell;
}

What I want to do is get the index of the textfield that was edited? 我要执行的操作是获取已编辑文本字段的索引? I wired up the textfield in the custom cell and made an action that executes on ending an edit: 我在自定义单元格中连接了文本字段,并执行了一个在结束编辑时执行的操作:

- (IBAction)getIndexForCaption:(id)sender {

[[[self.form valueForKey:@"photos"] objectAtIndex:cell.textfieldCaption.tag] setObject:cell.textfieldCaption.text forKey:@"caption"];

}

But how this is now, I dont have the "cell" so I get undeclared identifier "cell" error. 但是现在情况如何,我没有“ cell”,所以我得到未声明的标识符“ cell”错误。 How can I get the custom cell in this case? 在这种情况下,如何获取自定义单元格?

There are several options available to do this. 有几种方法可以做到这一点。 Personally, I would prefer make a subclass of UITextField with an extra property for the PhotoSummaryCell . 就个人而言,我更愿意为UITextField创建一个带有PhotoSummaryCell额外属性的子类。 You could set this property when the cell gets recycled, and this would make getting the index of the text field as easy as: 您可以在回收单元时设置此属性,这将使获取文本字段的索引变得简单:

NSIndexPath *indexOfTextField = [self.tableView indexPathForCell:textField.cell];

Then of course, you could step through the text fields view hierarchy until you find a cell, or save the index path's row into the textfields tag property as @rmaddy and @Martin R pointed out. 然后,当然,您可以逐步遍历文本字段视图层次结构,直到找到一个单元格为止,或者按照@rmaddy和@Martin R指出的那样将索引路径的行保存到textfields tag属性中。

Make sure that you declare your cell property as weak to avoid retain cycle. 确保将cell属性声明为weak以避免保留周期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM