一、scrollToRowAtIndexPath 会发生崩溃:
//scroll to previously selected cell
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.lastIdx inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
崩溃的原因是:
比如数据源中有3个元素,而tableview中只显示了2个元素,当调用scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:2
时肯定就出错了。
解决方法是: 在调用这个方法之前刷新数据源
[self.tableView reloadData];
二、不执行或者执行错误的问题:
背景:在用纯代码(purelauout布局的情况下),给tableView设置了约束,但是没有给frame
- (void)initializeTableView
{
self.view.backgroundColor = HEXCOLOR(0xf0f0f0);
self.tableView = [[TPKeyboardAvoidingTableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
self.tableView.delegate = self;
self.tableView.dataSource = self;
self.tableView.backgroundColor = HEXCOLOR(0xf0f0f0);
[self.view addSubview:self.tableView];
[self.tableView tn_pinEdgeToSuperviewEdge:TNAEdgeLeading withInset:0.0f];
[self.tableView tn_pinEdgeToSuperviewEdge:TNAEdgeTop withInset:self.topBarView.height];
[self.tableView tn_matchDimension:TNADimensionWidth toDimension:TNADimensionWidth ofView:self.view];
[self.tableView tn_pinEdgeToSuperviewEdge:TNAEdgeBottom withInset:0.0f];
}
在执行scrollToRowAtIndexPath 是不知道tableView的frame的,所有滚冬到相对应的cell就有问题。
self.tableView = [[TPKeyboardAvoidingTableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
就可以。
其次,防止crash,可以设置代码保护:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
//protect code
if ([self tableView:self.tableView numberOfRowsInSection:[NSIndexPath indexPathForRow:self.lastIdx inSection:0].section] > [NSIndexPath indexPathForRow:self.lastIdx inSection:0].row) {
if (self.lastIdx != NSNotFound && self.lastIdx < self.holder.customers.count) {
//scroll to previously selected cell
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.lastIdx inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
self.lastIdx = NSNotFound;
}
}
}
因为业务本身只有一组,所以我没有设置组的判断,可以的话设置上,注意要实现tableView的组方法,否则会报 unresgonized selector !!!