本文介绍了如何从其子视图中获取UITableViewCell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在每个 UITableViewCells UITableView ,其中包含 UITextField C $ C>。我的ViewController中有一个方法,它处理每个单元格的文本字段的在结束时退出事件,我想要做的是用新文本更新我的模型数据。

I have a UITableView with a UITextField in each of the UITableViewCells. I have a method in my ViewController which handles the "Did End On Exit" event for the text field of each cell and what I want to be able to do is update my model data with the new text.

我目前拥有的是:

- (IBAction)itemFinishedEditing:(id)sender {
    [sender resignFirstResponder];

    UITextField *field = sender;
    UITableViewCell *cell = (UITableViewCell *) field.superview.superview.superview;

    NSIndexPath *indexPath = [_tableView indexPathForCell:cell];

    _list.items[indexPath.row] = field.text;
}

当然要做 field.superview.superview.superview 有效,但看起来真的太乱了。有更优雅的方式吗?如果我将 UITextField 的标记设置为 indexPath.row > cellForRowAtIndexPath 即使在插入和删除行之后,该标记是否仍然正确?

Of course doing field.superview.superview.superview works but it just seems so hacky. Is there a more elegant way? If I set the tag of the UITextField to the indexPath.row of the cell its in in cellForRowAtIndexPath will that tag always be correct even after inserting and deleting rows?

对于那些密切关注的人,你可能会认为我有一个 .superview 太多了,对于iOS6你是对的。但是,在iOS7中,在单元格的内容视图和单元格本身之间的层次结构中有一个额外的视图(NDA阻止我形成详细说明)。这准确地说明了为什么做superview的事情有点hacky,因为它取决于知道如何实现 UITableViewCell ,并且可以打破操作系统的更新。

For those paying close attention you might think that I have one .superview too many in there, and for iOS6, you'd be right. However, in iOS7 there's an extra view (NDA prevents me form elaborating) in the hierarchy between the cell's content view and the cell itself. This precisely illustrates why doing the superview thing is a bit hacky, as it depends on knowing how UITableViewCell is implemented, and can break with updates to the OS.

推荐答案

由于你的目标是获取文本字段的索引路径,你可以这样做:

Since your goal is really to get the index path for the text field, you could do this:

- (IBAction)itemFinishedEditing:(UITextField *)field {
    [field resignFirstResponder];

    CGPoint pointInTable = [field convertPoint:field.bounds.origin toView:_tableView];    

    NSIndexPath *indexPath = [_tableView indexPathForRowAtPoint:pointInTable];

    _list.items[indexPath.row] = field.text;
}

这篇关于如何从其子视图中获取UITableViewCell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 22:42