今天在UITableView加入TableFooterView后出现NSRangeException异常,报错如下:
Terminating app due to uncaught exception ‘NSRangeException’, reason: ‘-[UITableView scrollToRowAtIndexPath:atScrollPosition:animated:]: section (0) beyond bounds (0).
通过报错的reason可以了解到是由于设置scrollToRowAtIndexPath属性的原因,根据报错的行数,找到报错的具体代码:
-(void)setFistVisibleRecord:(int)recordIndex{ [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:recordIndex/_columnSize inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO]; }
这段代码是用来设置第一个可见的cell记录。
当然如果将这个方法中的代码先注释掉,然后加载TableFooterView就没有了异常,但造成这个异常的原因也就确定了就是由于设置scrollToRowAtIndexPath属性造成的,通过查资料了解到造成这个异常的根本原因是由于在程序执行到setFistVisibleRecord方法时,UITableView的数据还没有加载造成的,所以在设置scrollToRowAtIndexPath属性之前需要强制让UITableView重新加载一边数据,具体代码:
-(void)setFistVisibleRecord:(int)recordIndex{ [_tableView reloadData]; [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:recordIndex/_columnSize inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO]; }
上述代码,红色部分是新加入的代码。