didSelectRowAtIndexPath返回错误的IndexPath

时间:2010-11-07 18:14:05

标签: iphone objective-c uitableview didselectrowatindexpath nsindexpath

我遇到了一个非常令人费解的错误。我的UITableView的第一个行返回 1 第二个在indexPath中返回 0 !怎么可能呢?

在我的` - (void)viewDidLoad`中,一切都还可以。我正在用

成功突出显示第一行
currentRow = 0;
[tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:currentRow inSection:0] 
  animated:NO scrollPosition:UITableViewScrollPositionNone];

我有变量currentRow用于跟踪选择哪一行(另一个控件根据当前选择的那个进行更改)。

现在在我的`didDeselectRowAtIndexPath`委托函数中我有:

-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
...
NSLog(@"IndexPath: %@", [indexPath description]);
}

日志显示以下内容:

当我触摸第二行时,

IndexPath: <NSIndexPath 0x79509d0> 2 indexes [0, 0] 当我触摸第一行IndexPath: <NSIndexPath 0x79509d0> 2 indexes [0, 1]

没有行插入或删除或排序等,甚至没有滚动。它是一个简单的UITableView,分组样式,有1个部分和3行。可能导致这种情况的原因是什么?

感谢您的帮助,
小号

2 个答案:

答案 0 :(得分:228)

您已实施didDeselectRowAtIndexPath。当行不再被选中时将被触发。

当您触摸第二行时,第一行不再被选中,因此将显示[0,1]。
当您再次触摸第一行时,第二行现在不再被选中,因此将显示[0,0]。

完全可以预期。

如果您需要在选择行时进行响应,请实施didSelectRowAtIndexPath

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //                                       ^
    ...

    NSLog(@"IndexPath: %@", [indexPath description]);
}

答案 1 :(得分:3)

尽管有标题,但重载方法实际上是didDeselectRowAtIndexPath,所以听起来行为是正确的 - 当触摸第1行时,第0行被取消选择,反之亦然。