在UITableView中获取所有单元格?

Jos*_*ane 2 iphone objective-c uitableview ipad

我需要在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;
}
Run Code Online (Sandbox Code Playgroud)

我已经取得了一些成功,但是我发现它在细胞不可见时会崩溃.那么我怎样才能获得UITableView中所有单元格的数组,无论它们是否可见?

Nen*_*d M 7

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

因此,您需要在代码中"禁用"单元格重用机制.这可以通过不在表视图数据源委托dequeueReusableCellWithIdentifiercellForRowAtIndexPath方法内出列(即不再使用该方法)您的单元格,并通过传递nil作为reuseIdentifier单元格init方法(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.
Run Code Online (Sandbox Code Playgroud)