美文网首页
UITableView 在reloadData同时滚动到底部

UITableView 在reloadData同时滚动到底部

作者: jolinpz | 来源:发表于2018-01-22 01:37 被阅读0次

    把UITableView滚动到底部是很简单的UI开发问题,调用下相关API就能完成,比如说设置下contentOffset。

    @implementation UITableView (Extension)
    
    - (CGFloat)verticalOffsetOnBottom {
        CGFloat viewHeight = self.bounds.size.height;
        CGFloat contentHeight = self.contentSize.height;
        CGFloat topInset = self.contentInset.top;
        CGFloat bottomInset = self.contentInset.bottom;
        CGFloat bottomOffset = floorf(contentHeight - bottomInset - topInset - viewHeight);
        return MAX(bottomOffset, 0);
    }
    
    - (void)scrollToBottom:(BOOL)animated {
        CGPoint bottomOffset = CGPointMake(0, [self verticalOffsetOnBottom]);
        [self setContentOffset:bottomOffset animated:animated];
    }
    
    @end
    

    但是想在reloadData同时滚动到底部,则很容易出现位置偏差或者动画抖动,因为UITableView在reloadData时还没有计算出准确的contentSize,所以contentOffset是错的。

    在stackoverflow上,基本是建议用dispatch_after或者performSelector:withObject:afterDelay:做少量延迟(如0.1s)再滚动,经测试效果不好,而且在不同性能的设备上时延也很难控制。

    最近做需求也遇到这个问题,设计要求在点击某个按钮时,刷新页面同时滚动到底部,经过各种尝试终于完美解决。

    - (IBAction)buttonTapped:(id)sender {
        [self.tableView reloadData];
        [self scrollToBottom];
    }
    
    - (void)scrollToBottom {
        [self.tableView beginUpdates];
        [self.tableView scrollToBottom:YES];
        [self.tableView endUpdates];
    }
    

    相关文章

      网友评论

          本文标题:UITableView 在reloadData同时滚动到底部

          本文链接:https://www.haomeiwen.com/subject/jhecaxtx.html