【问题标题】:Accessing CollectionView indexPath.row in prepareForSegue在 prepareForSegue 中访问 CollectionView indexPath.row
【发布时间】:2015-01-06 02:47:48
【问题描述】:

我正在尝试从我的 prepareForSegue 函数中的 collectionView 访问 indexPath.row 变量。我有以下代码:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    let selectedIndex = collectionView.indexPathsForSelectedItems() as NSIndexPath
    //let myIndexPath = self.collectionView.indexPathForCell(cell: LocalFeedCollectionViewCell.self)

    if (segue.identifier == "toFullImage")
    {
        var fullImageVC: FullImageViewController = segue.destinationViewController as FullImageViewController
        fullImageVC.imageTitle = self.imageTitles[selectedIndex.row]
    }
}

我收到以下 selectedIndex 错误 - “(UICollectionView, numberOfItemsInSection: Int) -> Int”没有名为“indexPathsForSelectedItems”的成员。在 Objective-C 中,我看到以下解决方案

NSIndexPath *indexPath = [self.collectionView indexPathForCell:sender];

但我不确定如何快速实现它/是否可行。

谢谢

【问题讨论】:

  • 我想我可能已经通过将变量设为变量“var rowPath: Int = 0”然后将其设置为等于 indexPath.row 来解决问题。然后我可以写“fullImageVC.imageTitle = self.imageTitles[rowPath]”
  • 您在问题中遇到的错误实际上是在那段代码中生成的吗?在您提供的代码中,我没有看到对 numberOfItemsInSection 的任何引用。
  • 是的,错误是在“let selectedIndex”行中发现的

标签: ios swift uicollectionview nsindexpath


【解决方案1】:

一个明显的问题是indexPathsForSelectedItems() 没有返回可以转换为 NSIndexPath 的东西。它返回一个数组。如果您尝试向下转换为索引路径数组,则需要向下转换为[NSIndexPath],而不是NSIndexPath

【讨论】:

  • 我也看到了,但它似乎与问题中的类型错误不匹配。不过,我不相信类型错误实际上是在该函数中(因为它引用了numberOfItemsInSection)。
  • 这并不重要。该行有一个编译错误,这就是它的原因。如果您尝试他的代码并将他的NSIndexPath 更改为[NSIndexPath],那么该行上的编译错误实际上会消失。他的代码可能还有其他问题——我不知道——但这就是那个问题的答案。
【解决方案2】:

sender 参数是集合视图的单元格。所以首先将其转换为UICollectionViewCell,然后从集合视图中询问 indexPath。这是一个示例

if let cell = sender as? UICollectionViewCell {
    if let indexPath = collectionView.indexPathForCell(cell) {
        // use indexPath here
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 2017-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    相关资源
    最近更新 更多