我需要获取 UITableView 中所有单元格的数组。我目前使用以下方法:
-(NSArray *)allTableViewCellsArray
{
NSMutableArray *cells = [[NSMutableArray alloc] init];
for (NSInteger j = 0; j < [tableView numberOfSections]; ++j)
{
for (NSInteger i = 0; i < [tableView numberOfRowsInSection:j]; ++i)
{
[cells addObject:[tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:j]]];
}
}
return cells;
}
我已经取得了一些成功,但是我发现当单元格不可见时它会崩溃。那么如何获取 UITableView 中所有单元格的数组,无论它们是否可见?
最佳答案
您是否在实现中重复使用表格单元格?如果是这样,我认为由于 UITableView 的单元格重用逻辑,您无法从 UITableView 中获取所有 UITableViewCell 对象。
因此,您需要在代码中“禁用”单元格重用机制。
这可以通过不使 dequeueReusableCellWithIdentifier
内的单元出队(即不再使用 cellForRowAtIndexPath
方法)来完成。 TableView 数据源委托(delegate)的方法,并为 reuseIdentifier
传递 nil单元格初始化方法的属性 ( initWithStyle:reuseIdentifier:
)。
然后你的allTableViewCellsArray
方法也许可行!
但我认为你仍然不会有任何运气来完成这一任务。
来自 Apple 文档 [tableView cellForRowAtIndexPath:]
:
Return Value An object representing a cell of the table or nil if the cell is not visible or indexPath is out of range.
关于iphone - 获取 UITableView 中的所有单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13699773/