UITableView:加载所有单元格



是否可以在加载视图时加载UITableView的所有单元格,以便在滚动时不加载这些单元格?(我会在进行此操作时显示加载屏幕)

拜托,这是我项目的唯一方法(抱歉太复杂了,无法解释为什么^^)

编辑:

好吧,让我向你解释一下,我肯定在做什么:

- (UITableViewCell *)tableView:(UITableView *)tableView
     cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   NSString *cellIdentifier = [NSString stringWithFormat:@"Identifier %i/%i", indexPath.row, indexPath.section];
   CustomTableCell *cell = (CustomTableCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
   NSDictionary *currentReading;
   if (cell == nil)
   {
       cell = [[[CustomTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
       UILabel *label;
       UIView *separator;
       if(indexPath.row == 0)
       {
           // Here I'm creating the title bar of my "table" for each section
       }
       else
       {
           int iPr = 1;
           do
           {
               currentReading = [listData objectAtIndex:iPr-1];
               iPr++;
           } while (![[currentReading valueForKey:@"DeviceNo"] isEqualToString:[devicesArr objectAtIndex:indexPath.section]] || 
                      [readingresultsArr containsObject:[currentReading valueForKey:@"ReadingResultId"]]);
           [readingresultsArr addObject:[currentReading valueForKey:@"ReadingResultId"]];
           //
           // ...
           //
       }
    }
    return cell;
}

我的错误发生在do while循环中:"listData"是一个包含多个字典的数组。我的问题是,当我慢慢向下滚动表格时,一切都很好,但当我快速滚动到视图的末尾,然后滚动到中间时,我会得到iPr超出数组范围的错误。因此,问题是,第一节的最后一行已经添加到"readingresultsArr"中,但尚未加载或希望再次加载。这就是为什么我想一次加载所有单元格的原因。

您可以通过调用来预分配所有单元格

[self tableView: self.tableView cellForRowAtIndexPath: indexPath];

表中的每一行。将上面的行放入一个适当的for循环中,并在viewDidAppear中执行此代码。

然而,问题是tableView不会保留所有这些单元格。它会在不需要它们的时候丢弃它们。

您可以通过在UIViewController中添加一个NSMutableArray,然后缓存在cellForRowAtIndexPath中创建的所有单元格来解决这个问题。如果表在其生存期内有动态更新(插入/删除),则还必须更新缓存数组。

在uiscrollview 上放置uitableview

例如,您希望完整列表uitableview的高度为1000

然后将uiscrollview内容大小设置为320X1000并设置合适的视图高度为1000

则所有单元格加载其内容,即使在屏幕中不可见

在我的例子中,我使用automaticDimension作为单元格高度,并将estimatedRowHeight设置为较小,这就是为什么tableview加载所有单元格的原因。

这里和这里的一些答案建议使用automaticDimension作为单元格高度,并将mytable.estimatedRowHeight设置为非常低的值(如1)。


iOS 15开始,这种方法似乎不再奏效。因此,实现表到";负载";所有单元格都可以自动滚动到最后一个单元格。根据表格的高度和可以显示的行数,一些单元格会被丢弃,但每个单元格都会被加载并至少显示一次。

mytable.scrollEnabled = YES;
NSIndexPath* indexPath = [NSIndexPath indexPathForRow:cellCount - 1 inSection:0];
[mytable scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
mytable.scrollEnabled = NO;

如果你想再次向上滚动,只需滚动到顶部,如图所示。

根据juancazalla的评论,我发现如果您有一个使用automaticDimension的tableView,那么通过将estimatedRowHeight设置为低值(如1)可以最好地同时加载所有单元格。

最新更新