UITableView reloadData tableView上下抖动

  • 最近做的一个项目,有一个选取照片上传服务器的功能,图片展示用的tableView,高度自适应,代码如下:
- (void)initSubviews {
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.rowHeight = UITableViewAutomaticDimension;
    _tableView.estimatedRowHeight = 44; 
    _tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
}
  • cell代码(cell里面是一个collectionView):
- (void)awakeFromNib {
    [super awakeFromNib];
    
    UICollectionViewFlowLayout *flowlayout = [[UICollectionViewFlowLayout alloc] init];
    flowlayout.minimumInteritemSpacing = 0;
    flowlayout.minimumLineSpacing = 0;
    flowlayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowlayout];
    _collectionView.scrollEnabled = YES;
    _collectionView.backgroundColor = [UIColor whiteColor];
    [_collectionView registerNib:[UINib nibWithNibName:@"ApplyPatrolImageCollectionCell" bundle:nil] forCellWithReuseIdentifier:@"ApplyPatrolImageCollectionCell"];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [self.collectionBGView addSubview:_collectionView];
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.collectionBGView);
    }];
}
702C493F-B488-4078-A2F7-56F95D30AE77.png
- (void)setDataArray:(NSArray *)dataArray {
    _dataArray = [dataArray copy];
    
    int count = (int)_dataArray.count;
    if (count % 3 == 0) {
        _heightConstraint.constant = count / 3 * collectionItemHeight;
    } else {
        _heightConstraint.constant = (count / 3 + 1) * collectionItemHeight;
    }
    
    [self.collectionView reloadData];
    
}
  • 我是通过设置_heightConstraint.constant来确定cell高度,从而实现自适应,实际操作的时候,cell高度展示没问题,效果如下:

    IMG_0966.PNG

  • 然而,在添加图片,刷新数据的时候,tableView会快速的上下抖动一下,用户体验很不好,于是乎在网上各种百度,网上说的解决办法五花八门(有的说不适用高度自适应,通过代理设置高度能解决,有的说设置estimatedRowHeight = 0,然并卵),各种尝试都没有解决我的问题。

解决办法

  • 最后我想了一下,是不是_tableView.estimatedRowHeight = 44这个高度设置的少了,于是乎我设置了一个更大的数值400(预期的cell高度最高360),运行发现,问题解决了
- (void)initSubviews {
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.rowHeight = UITableViewAutomaticDimension;
    _tableView.estimatedRowHeight = 400; //设置数值大一些,防止闪屏出现
    _tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
}
  • 具体原因,我也不知道,希望对大家有所帮助,也希望有大神指点一下迷津。

你可能感兴趣的:(UITableView reloadData tableView上下抖动)