tableView 自动滚动到底部

本文介绍了一个iOS应用中UITableView的高效更新方法。通过监测TableView的高度变化来决定采用插入新行还是重新加载数据的方式进行更新,同时提供了调整TableView内边距及滚动到底部的实现细节。

- (void)addData:(id)object{
   
   
    NSInteger count = self.dataArray.count;
   
   
   
    _index ++;
    NSString * str = [NSString stringWithFormat:@"当前第%zd行",_index];
    [self.dataArray addObject:str];
   
    if (count * 44.0f > self.tableView.height) {
        NSMutableArray *insert = [[NSMutableArray alloc] init];
        for (NSInteger index = count; index < count+1; index++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
            [insert addObject:indexPath];
        }
        [self.tableView beginUpdates];
        [self.tableView insertRowsAtIndexPaths:insert withRowAnimation:UITableViewRowAnimationFade];
        [self.tableView endUpdates];
        [self.tableView layoutIfNeeded];
       
        [self changeInsets:object];
        [self scrollToBottom];
    } else {
        [self.tableView reloadData];
    }
 
   
  
}
 
 
- (void)changeInsets:(id)object
{
    CGFloat height = 0;
    height += 44.0f;
//    for (NTESMessageModel *model in newModels) {
//        height += 44.0f;
//    }
    UIEdgeInsets insets = self.tableView.contentInset;
    CGFloat contentHeight = self.tableView.contentSize.height - insets.top;
    contentHeight += height;
    CGFloat top = contentHeight > self.tableView.height? 0 : self.tableView.height - contentHeight;
    insets.top = top;
   
//    MyLog(@"tableViewHeight == %f",self.tableView.height);
//    MyLog(@"top == %f",top);
   
    self.tableView.contentInset = insets;
}
 
- (void)scrollToBottom
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        CGFloat offset = self.tableView.contentSize.height - self.tableView.height;
        [self.tableView scrollRectToVisible:CGRectMake(0, offset, self.tableView.width, self.tableView.height) animated:YES];
    });
}

转载于:https://www.cnblogs.com/Jackie-subDai/p/9290099.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值