簡體   English   中英

當重新加載具有不斷變化的單元格高度的單元格時,UITableView會滾動到頂部

[英]UITableView scrolls to top when reloading cells with changing cell heights

我有一個表視圖,它包含一個占位符,當它加載到圖像中。 加載圖像時,我調用reloadRowsAtIndexPaths:withRowAnimation: . 此時,單元格會根據圖像的大小更改高度。 當發生這種情況時,我希望表視圖的內容偏移保持在原位,並且下面的單元格可以進一步向下推,就像您想象的那樣。

我得到的效果是滾動視圖滾動回到頂部。 我不知道為什么會這樣,我似乎無法阻止它。 reloadRows行之后放置beginUpdates()endUpdates()無效。

我正在使用estimatedRowHeight ,因為我的表視圖可能有數百行不同的高度。 我也在實現tableView:heightForRowAtIndexPath: .

編輯:我已經設置了一個演示項目來測試這個,並且無可否認我無法獲得演示項目來重現這種效果。 我會繼續努力。

這是estimatedRowHeight的一個問題。

estimatedRowHeight與實際高度的差異越大,表格在重新加載時可能跳得越多,尤其是滾動得越遠。 這是因為表的估計大小與其實際大小完全不同,迫使表調整其內容大小和偏移量。

最簡單的解決方法是使用非常准確的估算。 如果每行的高度變化很大,請確定行的中間高度,並將其用作估計值。

始終更新主線程上的UI。 所以只是放置

[self.tableView reloadData];

在主線程內:

dispatch_async(dispatch_get_main_queue(), ^{
     //UI Updating code here.
     [self.tableView reloadData];
});

我遇到了同樣的問題,並通過這種方式決定:在加載時保存單元格的高度,並在tableView:estimatedHeightForRowAtIndexPath給出准確的值tableView:estimatedHeightForRowAtIndexPath

// declare cellHeightsDictionary
NSMutableDictionary *cellHeightsDictionary;

// save height
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    [cellHeightsDictionary setObject:@(cell.frame.size.height) forKey:indexPath];
}

// give exact height value
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSNumber *height = [cellHeightsDictionary objectForKey:indexPath];
    if (height) return height.doubleValue;
    return UITableViewAutomaticDimension;
}

我看到了這一點,對我有用的修復方法是選擇估計的行高,這是可能行中最小的行。 當非預期的滾動發生時,它最初被設置為最大可能的行高。 我只是使用單個tableView.estimatedRowHeight屬性,而不是委托方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM