(七十一)关于UITableView退出崩溃的问题和滚动到底部的方法

【TableView退出崩溃的问题】

最近在使用TableView时偶然发现在TableView中数据较多时,如果在滚动过程中退出TableView到上一界面,会引起程序的崩溃,经过网上查阅和思考我发现这种情况出现在一个UIView控制器拥有一个TableView,TableView无法在UIView销毁前完全销毁,从而继续调用dataSource,而这时候UIView已经不可用了,会引发野指针错误。

避免方法很简单,只需要在UIView的dealloc方法中把dataSource设为nil即可:

- (void)dealloc{
    
    self.tableView.dataSource = nil;
    
}

【TableView滚动到底部】

对于即时聊天等应用,常常需要在新数据到来时把TableView滚动到底部,这个需求可以通过TableView的scrollToRowAtIndexPath::实现,需要传入要滚动到的cell位置和滚动位置。

需要传入indexPath的最后一个位置,也就是要显示的数据数组的最后一个元素的索引,位置为底部,枚举名为

UITableViewScrollPositionBottom,如下:

Tip:一定要注意在没有数据时会造成indexPath.row=-1,此时应当直接返回。

- (void)scrollToTableBottom{
    
    if (_array.count < 1) {
        return;
    }
    NSInteger lastRow = _array.count - 1;
    NSIndexPath *lastPath = [NSIndexPath indexPathForRow:lastRow inSection:0];
    [self.tableView scrollToRowAtIndexPath:lastPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    
}


原文地址:https://www.cnblogs.com/aiwz/p/6154143.html