首页 > 解决方案 > 准备从collectionviewcell 中的segue 不显示索引项

问题描述

我正在尝试从 collectionViewController 转到另一个视图控制器,并且我还尝试获取索引并适当地传递数据,但是当我选择一个单元格时,detailVC 只会显示,但没有打印任何内容或任何东西

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

        if segue.identifier == DETAIL_VC {

            print("ITEM SELECTED ")
            let vc = segue.destination as! DetailVC
            guard let selectedIndexPath = sender as? IndexPath else { return }
            let flickerPhoto = ServiceProvider.instance.flickerPhotos[selectedIndexPath.item]

            print("ITEM SELECTED ")
            vc.titleLabel.text = flickerPhoto.title
        }
}

什么都没有打印

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {


        let flickerPhoto = ServiceProvider.instance.flickerPhotos[indexPath.item]
        let destinationVC = storyboard?.instantiateViewController(withIdentifier: DETAIL_VC) as! DetailVC
        destinationVC.titleLabel.text = flickerPhoto.title

    }

我得到了错误Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

标签: iosswift

解决方案


您需要将DETAIL_VC源vc(而不是单元格)的黄色图标命名的segue连接到目标,并在里面使用它didSelectItemAt

self.performSegue(withIdentifier:DETAIL_VC,sender:indexPath)

当您在加载 vc 之前访问一个为 nil 的插座时它会崩溃,您可以尝试将数据作为字符串发送并将其设置viewDidLoad在目标 vc 中

destinationVC.titleValue = flickerPhoto.title

class DetailVC:UIViewController {

    var titleValue:String = ""

   // set it to the label text in `viewDidLoad`

    override func viewDidLoad() {

      super.viewDidLoad()

        self.titleLabel.text = titleValue
     }
}

推荐阅读