我想对我的应用程序中的行进行编号,就像在 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 中正确编号每一行的问题?
最佳答案
您必须执行以下操作:
使用第一种方法,在
cellForRowAtIndexPath
方法中设置标签文本删除所需的行
现在不要重新加载整个表格 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];
}
关于ios - 如何对 UITableView 中的行进行编号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31761988/