ios常用功能

setContentOffset位置不对

2020-09-03  本文已影响0人  th先生
[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。解决了问题。

上一篇下一篇

猜你喜欢

热点阅读