CollectionView Segue在接收ViewController时发现nil

时间:2018-05-17 23:28:29

标签: ios swift uicollectionview segue uistoryboardsegue

我有一个集合视图,它在索引中选择一个Item并对下一个ViewController执行segue。当呈现下一个ViewController时,我的对象的值为 page.on('response', response => { // allow only XHR if ('xhr' !== response.request().resourceType()){ return ; } console.log(response.url()); }); await page.click('span#first'); await page.click('span#second'); await page.click('span#third');

以下是collectionView中的调用:

nil

请注意,guard语句正在进行,如果我从adArray打印一个值,它在此函数中有值。

执行打开右侧ViewController的segue后,广告对象始终为零。

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    guard let adViewVC = storyboard?.instantiateViewController(withIdentifier: adViewPageID) as? AdViewPageVC else {return}
    let adChoice = adArray[indexPath.row]
    adViewVC.advertisement = adChoice
    performSegue(withIdentifier: adViewPageSegue, sender: self)
}

即使我在集合视图的var advertisement : Advertisement! override func viewDidLoad() { super.viewDidLoad() let title = advertisement.title print(title) } 函数的赋值期间看到它具有值,也永远不会获得对象的值。

我在这里缺少什么?

2 个答案:

答案 0 :(得分:1)

您应该在advertisement函数中设置prepare(for:sender:)变量。您正在使用didSelect函数创建的视图控制器。

添加如下内容:

func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let viewController = segue.destination as? PlayerViewController {
        let adChoice = adArray[sender]
        viewController.advertisement = sender as? STZMediaItem
    }
}

并将您的didSelect函数更新为:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    performSegue(withIdentifier: adViewPageSegue, sender: indexPath)
}

答案 1 :(得分:1)

当用户点击collectionViewCell时,应用应该使用indexPath作为发件人执行segue:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    performSegue(withIdentifier: adViewPageSegue, sender: indexPath)
}

并使用prepare(for:sender:)方法准备所有必要的内容。而且您不必从故事板初始化viewController。 segue.destination就足够了。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let identifier = segue.identifier {
        if identifier == adViewPageSegue {
            guard let adViewVC = segue.destination as? AdViewPageVC else {return}
            let indexPath = sender as! IndexPath
            let adChoice = adArray[indexPath.row]
            adViewVC.advertisement = adChoice
        }
    }
}