【问题标题】:Retrieving indexpath for a selected UICollectionViewCell during PreparetoSegue?在 PreparetoSegue 期间检索选定 UICollectionViewCell 的索引路径?
【发布时间】:2017-05-04 17:24:07
【问题描述】:

使用 collectionViewCells 并尝试通过 segue 将数据发送到下一个 ViewController。虽然获取 indexPath 并不像在 tableViewCell 中那样简单,但我可以做这样的事情来获取它,但是我仍然收到“在展开可选值时意外发现 nil”错误。

代码如下:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if let cell = sender as? MainCollectionViewCell {
    if let indexPath = self.collectionview.indexPath(for: cell) {
        // use indexPath
    print(indexPath.row)
    let destvc: H1ViewController = segue.destination as! H1ViewController
  destvc.backgroundimg.image = UIImage(named: magazines[indexPath.row].image)

        }
    }

}

我正在打印 indexpath.row 并获取值。所以我确信就它而言我很好。我正在使用 if let 来确保我没有强行展开。这里有什么问题?

【问题讨论】:

  • 对于 segue.destination 为! H1ViewController 做一个 if let,这样你就可以看到它是正确的类型。也尝试使用调试器。
  • 另外,这发生在运行时并且肯定不是编译器错误,所以我建议删除该标签。
  • @Gerriet 刚刚尝试在该行也使用 if let 。还是什么都没有!
  • 嗯,错误说nil是什么值?
  • @O.Naeem,哪个是unexpectedly found nil while unwrapping an Optional value?添加您的错误日志

标签: ios swift uicollectionview


【解决方案1】:

解开了这个谜团。我在目标视图控制器中创建了一个字符串变量,并通过 segue 将图像的字符串名称发送到该变量。然后,在目标视图控制器的 ViewDidLoad 方法中,使用该字符串值来获取 imageviews IBOutlets 上的图像。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-10
    • 1970-01-01
    • 1970-01-01
    • 2013-06-16
    • 1970-01-01
    相关资源
    最近更新 更多