【问题标题】:iOS: editingStyleForRowAtIndexPath when adding a new celliOS:添加新单元格时编辑StyleForRowAtIndexPath
【发布时间】:2011-02-23 13:47:13
【问题描述】:

当用户使用以下代码将表格切换到编辑模式时,我正在向 UITableView 部分添加一行:

- (void) setEditing:(BOOL) editing animated:(BOOL) animated {
    [super setEditing:editing animated:animated];
    if (editing) {
        [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject: [NSIndexPath indexPathForRow:0 inSection:SECTION_SUPPLIERS]]   withRowAnimation:UITableViewRowAnimationFade];
    } 
}

要创建“添加新供应商...”行的对象。这可行,但是当表格想要获得编辑样式以便它可以添加加号或减号图标时,我遇到了问题。

- (UITableViewCellEditingStyle) tableView:(UITableView *) tableView editingStyleForRowAtIndexPath:(NSIndexPath *) indexPath {
    return ([self.tableView isEditing] && indexPath.row == 0) ? UITableViewCellEditingStyleInsert : UITableViewCellEditingStyleDelete;
}

顺序似乎是这样的:

  1. 表格切换到编辑状态。此时只有一个供应商行,因此它会查询行 == 0 的编辑样式。
  2. 新行的插入完成,然后再次触发另一个编辑样式查询,行 == 0。

因此,如果我使用此序列并使用行号和 tableView isEditing 来决定编辑样式图标,我最终会得到带有加号图标的添加新供应商行和当前供应商行。

插入一行并分配适当的编辑样式的最佳方法是什么 - 加号表示添加新行,减号表示任何其他行?

【问题讨论】:

    标签: ios uitableview


    【解决方案1】:

    您是否尝试过将“添加新...”行放在底部而不是顶部?而不是检查[indexPath row] == 0,而是检查[indexPath row] == [items count],您的tableView:numberOfRowsInSection: 实现如下所示:

    - (NSInteger)tableView:(UITableView *)tableView
     numberOfRowsInSection:(NSInteger)section {
        int numberOfRows = [items count];
    
        if ([self isEditing]) {
            numberOfRows++;
        }
    
        return numberOfRows;
    }
    

    这就是 iPhone Programming: The Big Nerd Ranch Guide 中的示例的工作原理。

    【讨论】:

    • 谢谢,我已经有了类似的代码。我想弄清楚的是如何在发送editingStyleForRowAtIndexPath 消息时判断正在查询哪个单元格。问题的一部分似乎是在执行插入时,UITableView 并没有实际添加单元格,因为代码还没有返回到运行循环。
    • 提供更多详细信息 - 如果我向 editorStyleForRowAtIndexPath 方法添加代码,该方法查询 UITableView 中的 indexPath 行。插入新单元格后,我仍然会取回当前单元格,因为 UITableView 还没有新的添加单元格。我必须等待运行循环执行并在此之前发生动画。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    • 2011-07-25
    • 2017-06-30
    相关资源
    最近更新 更多