ios - 如何对 UITableView 中的行进行编号

标签 ios objective-c uitableview

我想对我的应用程序中的行进行编号,就像在 Excel 中一样。我在单元格中为此使用了标签。我已经编写了一些完美执行此操作的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.numberlabel.text = [NSString stringWithFormat:@"%li.",(indexPath.row+1)];

    return cell;
}

但是问题是,每当我删除一行时,编号都不会刷新。所以我想,每当用户删除一行时,也许我会遍历每个单元格并再次设置数字。这是我所做的:

NSArray *cells = [tableView visibleCells];

int n = 0;

for (TableViewCell *cell in cells)
{
     n++;
     cell.numberlabel.text = [NSString stringWithFormat:@"%i.",n];
}

这很好用,但我再次遇到了另一个问题:表格 View 正在重用单元格,因此我无法迭代每个单元格,只能迭代实际在屏幕上的单元格。

所以我的问题是:即使用户开始删除行,我将如何解决在 TableView 中正确编号每一行的问题?

最佳答案

您必须执行以下操作:

  1. 使用第一种方法,在 cellForRowAtIndexPath 方法中设置标签文本

  2. 删除所需的行

  3. 现在不要重新加载整个表格 View ,而是对所有可见单元格使用reloadRowsAtIndexPaths。所有屏幕外单元格一旦可见,就会拥有正确的行号,因为它将在 cellForRowAtIndexPath 方法中设置。

示例:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Default" forIndexPath:indexPath];
    cell.textLabel.text = [NSString stringWithFormat:@"%li", indexPath.row +1];
    return cell;

}
- (NSArray *) tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"Delete" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {

        self.numberOfRows--;

        NSMutableArray *visibleCellIndexPaths = [[tableView indexPathsForVisibleRows] mutableCopy];
        [visibleCellIndexPaths filterUsingPredicate:[NSPredicate predicateWithFormat:@"row > %i",indexPath.row]];

        [tableView beginUpdates];

        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
        [tableView reloadRowsAtIndexPaths:visibleCellIndexPaths withRowAnimation:UITableViewRowAnimationFade];

        [tableView endUpdates];



    }];

    return @[deleteAction];

}

Example

关于ios - 如何对 UITableView 中的行进行编号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31761988/

相关文章:

ios - 无法将类型 '__NSCFString' 的值转换为 'NSData'

ios - UIPickerView有多个组件时如何只显示一个组件?

ios - Swift 支持继承类型

iphone - 非常奇怪的 UIView 位置问题

ios - 禁用自动滚动 UITableView

ios - 将 .txt 安全地保存在设备上

objective-c - 处理ARC中的指针对指针所有权问题

objective-c - EXC_BAD_ACCESS 切换到 ARC 时出错

ios - 使用 VSL 的 UITableview 标题水平和垂直约束

ios - UITableViewCell 分隔线在编辑期间出现