【问题标题】:indexPath Value of UICollectionViewUICollectionView 的 indexPath 值
【发布时间】:2012-10-06 15:21:30
【问题描述】:

当使用 UICollectionView 时,我对获取 didSelectItemAtIndexPath 方法的 indexPath 值感到困惑。

我在didSelectItemAtIndexPath 方法中使用了以下代码行:

//FileList is an NSArray of files from the Documents Folder within my app.
//This line gets the indexPath of the selected item and finds the same index in the Array
NSString *selectedItem = [NSString stringWithFormat:@"%@",[FileList objectAtIndex:indexPath.item]];

//Now the selected file name is displayed using NSLog
NSLog(@"Selected File: %@", selectedItem);

问题是 indexPath 总是返回 0(见下面的代码),因此只选择了 FileList NSArray 中的第一项。

我尝试了不同的参数,例如

  • indexPath.row
  • indexPath.item
  • 只是简单的indexPath

在以下 NSLog 语句中,所有这些都返回值 0:

NSLog(@"index path: %d", indexPath.item); //I also tried indexPath.row here

也许我只是不正确地格式化 NSString,但我不认为是这种情况,因为没有警告,我已经尝试在其他地方以不同的方式格式化它。

为什么 indexPath 总是返回 0?

任何帮助将不胜感激!谢谢!

【问题讨论】:

  • 请说明你如何格式化NSLog的字符串
  • .item 是这里的合适属性,但在功能上这与.row 没有什么不同。你需要展示更多——你怎么知道它是零?什么是文件列表?
  • 我已经编辑了这个问题,包括我如何格式化 NSLog 的字符串,我已经澄清了 FileList 是什么(请阅读注释代码)
  • 您的日志可能不是问题,但它过于复杂。只需这样做: NSLog(@"IndexPath: %d",indexPath.row);
  • 我已经简化了日志语句,但是我的问题与 NSLog 无关。我想知道为什么 indexPath 返回 0。

标签: objective-c ios nsindexpath uicollectionview


【解决方案1】:

冒着明显的风险,请确保您的代码在didSelectItemAtIndexPath 方法中,而不是didDeselectItemAtIndexPath 中。在后一种方法中,对于给定的触摸事件,您将获得非常不同的indexPath 值,并且很容易通过 Xcode 的代码完成插入错误的值。

【讨论】:

  • 该死的,自动完成
  • 让我加入感谢的合唱。这让我发疯了,我的眼睛没有真正读过它的方法名称。
【解决方案2】:

您使用的委托方法始终提供所选单元格的索引路径。 尝试在 NSLog 调用上使用断点进行调试。当调试器停止时,查看底部的调试区域并使用控制台(查看 => 调试区域 => 如果需要,激活控制台)。

在控制台输入:po indexPath

如果所选项目是 section:0 中列表的第 5 个(第一个部分,可能是唯一一个),您应该会看到类似的内容

<NSIndexPath 0xa8a6050> 2 indexes [0, 5]

希望这有助于弄清楚发生了什么。

【讨论】:

    猜你喜欢
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多