scrollToRowAtIndexPath出错

时间:2012-01-18 21:35:53

标签: iphone ios uitableview nsindexpath

使用我的使用tableview的应用程序时出现错误,错误如下所示。

2012-01-19 10:19:51.442 bcode[1176:207] *** Terminating app due to uncaught exception 'NSRangeException', reason: '-[UITableView scrollToRowAtIndexPath:atScrollPosition:animated:]: row (3) beyond bounds (3) for section (0).'
*** First throw call stack:
(0x16c3052 0x1920d0a 0x166ba78 0x166b9e9 0x68a136 0x3bfdf 0x6c2fbf 0x6c32d4 0x6c35d7 0x6d2666 0x87890e 0x878c17 0x878c86 0x62c499 0x62c584 0x2718e00 0x13614f0 0x15fa833 0x15f9db4 0x15f9ccb 0x1d05879 0x1d0593e 0x5fba9b 0x2838 0x2795 0x1)
terminate called throwing an exception(gdb) 
  

NSRangeException,-[UITableView scrollToRowAtIndexPath:atScrollPosition:animated:]
   第(3)行超出界限(3)的第(3)行。

当用户向下钻取导航视图时,他们可以从每个视图的tableview中选择一个单元格,稍后将用于构建搜索字符串。

但是我允许他们返回并更改他们的选择如果他们发生了错误..当用户更改父视图的值然后进入子视图时,只有当前一个选择超出条目数时才会发生此错误在当前的tableview ..

通常这不是一个大问题,但是在viewDidAppear中我调用的方法是滚动到之前选择的单元格...这显然是破坏应用程序并给我错误。

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    //Scroll to previously selected value
    [self.tableView scrollToRowAtIndexPath:oldCheckedIndexPath  atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
}

如何阻止执行此操作我在父视图中尝试了大约100个不同的if语句,并且子视图捕获新的索引路径并再次检查旧选择的索引路径然后设置

oldCheckedIndexPath = nil;
然而,无论如何它始终设法搞砸了。

4 个答案:

答案 0 :(得分:26)

干净的方式,假设self是tableView数据源:

检查表格视图中的部分数量:

if ( [self numberOfSectionsInTableView:self.tableView]
                                     > oldCheckedIndexPath.section 

并检查该部分中的行数:

  && [self tableView:self.tableView numberOfRowsInSection:
          oldCheckedIndexPath.section] > oldCheckedIndexPath.row )
   {
      [self.tableView scrollToRowAtIndexPath: // etc etc etc

或者,快速黑客:

@try {
    [self.tableView scrollToRowAtIndexPath: // etc etc etc 
}
@catch ( NSException *e )
{
    NSLog(@"bummer: %@",e);
}

答案 1 :(得分:4)

受到接受答案的启发:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
if ([self numberOfSectionsInTableView:self.tableView] > indexPath.section && [self tableView:self.tableView numberOfRowsInSection:indexPath.section] > indexPath.row) {
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

答案 2 :(得分:1)

我在调用scrollToRowAtIndexPath之前通过另一个选项解决了这个问题:此方法使用[yourtableviewobject reloadData];重新加载您的tableview,然后调用:

NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForRow:([messages count] - 1) inSection:0];
[objTableView scrollToRowAtIndexPath:scrollIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];

答案 3 :(得分:1)

我收到此错误,是因为我试图滚动到空tableView的第0行第0部分。确保您的tableData.count> 0。

相关问题