aro*_*oth 65
for (int section = 0; section < [tableView numberOfSections]; section++) {
for (int row = 0; row < [tableView numberOfRowsInSection:section]; row++) {
NSIndexPath* cellPath = [NSIndexPath indexPathForRow:row inSection:section];
UITableViewCell* cell = [tableView cellForRowAtIndexPath:cellPath];
//do stuff with 'cell'
}
}
Run Code Online (Sandbox Code Playgroud)
And*_*wPK 26
迭代UITableView中的每个可见单元格:
for (UITableViewCell *cell in self.tableView.visibleCells) {
NSIndexPath *cellIndexPath = [self.tableView indexPathForCell:cell];
Run Code Online (Sandbox Code Playgroud)
(编辑以更好地陈述答案,并希望为搜索结果更准确地编制索引,以便在将来为其他人节省更多时间)
(这建立在 aroths 的答案上。)
我喜欢将其定义为一个类别,UITableView以便它在任何地方都可用。
(正如多次提到的,你应该确定你真的想要迭代单元格本身。例如:UITableViewAccessoryCheckmark在将它设置为用户选择的单元格之前,我使用它来清除所有单元格中的's。一个很好的经验法则仅当数据源方法无法执行您需要的操作时才执行此操作。)
像这样定义:
- (void)enumerateCellsUsingBlock:(void (^)(UITableViewCell *cell))cellBlock {
NSParameterAssert(cellBlock != nil);
for (int section = 0; section < [self numberOfSections]; section++) {
for (int row = 0; row < [self numberOfRowsInSection:section]; row++) {
NSIndexPath *cellPath = [NSIndexPath indexPathForRow:row inSection:section];
UITableViewCell *cell = [self cellForRowAtIndexPath:cellPath];
if (cellBlock != nil) {
cellBlock(cell);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
像这样调用:
[self.tableView enumerateCellsUsingBlock:^(UITableViewCell *cell) {
NSLog(@"cell:%@", cell);
}];
Run Code Online (Sandbox Code Playgroud)
对块进行 typedef 也是一种很好的风格。
| 归档时间: |
|
| 查看次数: |
22514 次 |
| 最近记录: |