【问题标题】:Update UITableViewCell tag property after row is moved移动行后更新 UITableViewCell 标记属性
【发布时间】:2012-01-03 05:17:02
【问题描述】:

在我的应用程序中,当我在textFieldDidEndEditing: 中提交编辑更改时,我需要能够跟踪识别 UITextField 来自哪个单元格。为此,我只需在 tableview:cellForRowAtIndexPath: 中的单元格文本字段上设置 tag 属性。

当单元格被移动时,这会带来一些麻烦。例如,如果我将底部单元格向上移动到顶部,删除现在位于底部的单元格,然后尝试编辑我刚刚放置在顶部的单元格,我的应用程序将崩溃,因为标签属性仍为 8 (或其他数字),但我的数据源中没有这么多元素。

我试图通过更新tableView:moveRowAtIndexPath:toIndexPath:中的标签来解决这个问题

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
    NSString *siteToMove = [[sites objectAtIndex:[fromIndexPath row]] retain];

    [sites removeObjectAtIndex:[fromIndexPath row]];
    [sites insertObject:siteToMove atIndex:[toIndexPath row]];

    if ([toIndexPath section] == 1) {
        [[(BookmarkTextEntryTableViewCell *)[[self tableView] cellForRowAtIndexPath:toIndexPath] textField] setTag:[toIndexPath row]];
    }
}

但是,这不起作用,因为(BookmarkTextEntryTableViewCell *)[[self tableView] cellForRowAtIndexPath:toIndexPath] 返回移动行之前 存在的单元格。

【问题讨论】:

    标签: iphone ios uitableview tags


    【解决方案1】:

    在您的- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath 方法中,您可以遍历您可能已作为子视图添加到表中的所有UITextFields,然后检查并将新标签设置为-

    for (UIView* subview in [[self tableView] subviews]) {
     if ([subview isKindOfClass:[UITextField class]]) {  
      if(subview.tag==oldTag){
        subview.tag = newTag;
        break;
      }
     }
    }
    

    编辑:再三考虑,您可以重新加载表格数据,以防重置所有剩余单元格的标签。

    【讨论】:

      猜你喜欢
      • 2011-09-16
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多