2

我需要获取 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 中所有单元格的数组?

4

3 回答 3

7

您是否在实现中重复使用表格单元格?如果是这样,我认为您无法从 UITableView 中获取所有 UITableViewCell 对象,因为 UITableView 的单元格重用逻辑。

因此,您需要在代码中“禁用”单元重用机制。这可以通过不在表格视图数据源委托的方法中使dequeueReusableCellWithIdentifier单元格出列(即不再使用该方法)cellForRowAtIndexPath并通过将 nil 传递给reuseIdentifier单元格初始化方法 ( 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.
于 2012-12-04T09:44:17.060 回答
3

找到了解决方案。而不是在我选择的任何时间点抓取所有单元格,因为它不起作用;我创建了一个包含所有单元格的数组,这样每个单元格都可以迭代,这意味着我可以将它们全部添加到一个数组中。

我在willDisplayCell方法中这样做。

于 2012-12-04T10:26:40.050 回答
-2
for (UIView *view in TableView.subviews) {
    for (tableviewCell *cell in view.subviews) {
       //do
    }
}
于 2013-11-26T08:49:50.910 回答