setContentOffset位置不對

[tableView reloadData];

dispatch_async(dispatch_get_main_queue(), ^{
            CGPoint offset = CGPointMake(0,tableView.contentSize.height - tableView.frame.size.height);
            if (offset.y < 0) {
                return;
            }
            [tableView setContentOffset:offset animated:YES];
        });

遇到一個問題 ,就是在iOS13的機型上,

[tableView reloadData];
CGPoint offset = CGPointMake(0,tableView.contentSize.height - tableView.frame.size.height);
[tableView setContentOffset:offset animated:YES];

上面的代碼使用,沒有問題,即使offset.y小于0,大于0,tableView的滾動,UI也是正常的,沒有留出空白。
但是在iOS12上面,就會出現很大的空白,錯位問題。
可能是在iOS13上面,對setContentOffset進行了優化。很智能的規避了錯誤顯示。

通過查閱資料,[tableView setContentOffset:offset animated:YES];的執行時間,并不會在[tableView reloadData];完全reload完畢后才去調用,這倆屬于異步操作的。所以有時候tableView.contentSize獲取并不準確。
也就是有時候在reolad之后調用// [weakSelf.tableView scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionBottom animated:YES];會出現數據越界bug的情況。

[tableView setContentOffset:offset animated:YES],不管animated設置YES或者NO,在scrllView進行滾動的時候是不會執行的,必須是等scrollView停止了滑動才會執行。但是[tableView setContentOffset:offset]不受這個影響。

還有資料顯示,在[tableView reloadData];與[tableView setContentOffset:offset animated:YES];中間添加上
[tableView layoutIfNeeded]; //加上這段代碼,然后在初始化tableview的時候

tableView.estimatedRowHeight = 0
tableView.estimatedSectionHeaderHeight = 0
tableView.estimatedSectionFooterHeight = 0,

這樣獲取的tableView.contentSize比較準確。

即使這樣,由于我的項目進行了自動布局,布局時間有延遲,導致在數據源多的時候,還是有偏移量,于是就加入了dispatch_get_main_queue。解決了問題。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。