【问题标题】:didSelectRowAtIndexPath returns wrong IndexPathdidSelectRowAtIndexPath 返回错误的 IndexPath
【发布时间】:2011-05-06 08:41:12
【问题描述】:

我遇到了一个非常令人费解的错误。我的 UITableView 的 first 行返回 1second 一个返回 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] 当我触摸 second 行时, IndexPath: <NSIndexPath 0x79509d0> 2 indexes [0, 1] 当我触摸 first 行时。

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

感谢您的帮助,
S

【问题讨论】:

    标签: iphone objective-c uitableview didselectrowatindexpath nsindexpath


    【解决方案1】:

    你已经实现了didDeselectRowAtIndexPath。当行不再被选中时,它将被触发。

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

    这些都是意料之中的。

    如果您需要在行被选中时做出响应,请实现didSelectRowAtIndexPath

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

    【讨论】:

    • 嘿-当我自己阅读问题时,我错过了这一点。 :-) 当它被使用两次时,就像错过了“the”这个词。 ;-)
    • 我也是这样做的。多么令人沮丧。 Intellisense 在 99.9% 的情况下都很棒,但其他 0.1% 的情况......哇。
    • 我花了几个小时试图弄清楚 iOS 用我之前选择的行来呼叫我。我什么都试过了。令人惊讶的是,几个字母有多大的不同。谜团解开了。
    • 天啊,我差点开始一个新问题!该死的 XCode 自动完成功能!各地点赞!
    • 令人惊讶有多少人遇到过这个问题。我刚刚花了过去 2 个小时试图弄清楚到底发生了什么。我讨厌你自动完成。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-06
      • 2015-09-20
      • 2012-07-29
      • 1970-01-01
      • 1970-01-01
      • 2017-02-20
      相关资源
      最近更新 更多