假设我有一个有多行的UITableView.我希望在某个时间点将所有UITableViewCells作为NSArray.我试过了
[tableView visibleCells]
Run Code Online (Sandbox Code Playgroud)
但是这种方法存在问题:我不能拥有当前屏幕中当前不存在的所有单元格.所以我转向另一种方法:
-(NSArray *)cellsForTableView:(UITableView *)tableView
{
NSInteger sections = tableView.numberOfSections;
NSMutableArray *cells = [[NSMutableArray alloc] init];
for (int section = 0; section < sections; section++) {
NSInteger rows = [tableView numberOfRowsInSection:section];
for (int row = 0; row < rows; row++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath]; // **here, for those cells not in current screen, cell is nil**
[cells addObject:cell];
}
}
return cells;
}
Run Code Online (Sandbox Code Playgroud)
但似乎这种方法仍然无法获得那些未在屏幕上显示的细胞.谁可以帮我这个事?
Tob*_*obi 21
我认为这不可能,因为tableView不存储所有单元格.它使用缓存机制,该机制仅存储一些不可见的单元以供重用.
你为什么需要所有细胞?也许你可以实现,你正在尝试做什么,否则.
Vak*_*kas 14
这是Swift 3.0中最简单的解决方案
func getAllCells() -> [UITableViewCell] {
var cells = [UITableViewCell]()
// assuming tableView is your self.tableView defined somewhere
for i in 0...tableView.numberOfSections-1
{
for j in 0...tableView.numberOfRowsInSection(i)-1
{
if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: j, inSection: i)) {
cells.append(cell)
}
}
}
return cells
}
Run Code Online (Sandbox Code Playgroud)
小智 7
每次创建单元格时,都可以将其添加到NSMutableArray中,您可以在需要时解析它:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomCell *Cell = [self dequeueReusableCellWithIdentifier:@"Custom_Cell_Id"];
if (Cell == NULL)
{
Cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Custom_Cell_Id"]];
[Cells_Array addObject:Cell];
}
}
- (void) DoSomething
{
for (int i = 0;i < [Cells count];i++)
{
CustomCell *Cell = [Cells objectAtIndex:i];
//Access cell components
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
53987 次 |
| 最近记录: |