Swift: 关闭模态呈现的 UICollectionViewController,传递数据

Swift: Dismissing modally presented UICollectionViewController, pass data

我在 Swift 项目的故事板中有以下设置:

我有一个包含许多 UIColor 的数组:

let palette = [UIColor.greenColor(), UIColor.redColor(), ...]

用户可以点击"Button"标签栏按钮,第二个VC将以模态方式呈现(垂直覆盖)。他可以从那里从 collection 视图中选择一种颜色。第一个 VC 是 UIViewController,第二个是 UICollectionViewController。在第二个 VC 中,我有以下代码来处理颜色选择:

override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){
    println("select color with index \(indexPath.row)")
    //user selected color, dismiss modal view controller
    self.dismissViewControllerAnimated(true, completion: nil)
}

如何将选定的颜色传回我的第一个视图控制器?我试过了:

override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){
    let vc = self.storyboard?.instantiateViewControllerWithIdentifier("FirstViewController") as FirstViewController
    // now, in FirstViewController, set backgroundColor of backgroundView with user selected value
    vc.backgroundView.backgroundColor = palette[indexPath.row]
    //user selected color, dismiss modal view controller
    self.dismissViewControllerAnimated(true, completion: nil)
}

上面的代码给了我Unexpectedly found nil while unwrapping Optional value

似乎连实例化的时候,backgroundView.backgroundColor也不可用

我也试过在dismissViewController的completion块中执行上面的代码,同样报错:

override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){
    //user selected color, dismiss modal view controller
    self.dismissViewControllerAnimated(true, completion: {
    let vc = self.storyboard?.instantiateViewControllerWithIdentifier("FirstViewController") as FirstViewController
    // now, in FirstViewController, set backgroundColor of backgroundView with user selected value
    vc.backgroundView.backgroundColor = palette[indexPath.row]
    })
}

非常感谢您的任何建议,我对此真的很迷茫。如果有任何不清楚的地方,请告诉我,我很乐意提供更多信息。

This blog post including full source code in Objective-C 帮我解决了问题。相关代码片段翻译成 Swift:

@IBAction func unwindToSegue (segue : UIStoryboardSegue) {

    if segue.sourceViewController.isKindOfClass(BackgroundColorCollectionViewController) {
        let vc = segue.sourceViewController as BackgroundColorCollectionViewController
        if (vc.selectedColor != nil) {
            self.view.backgroundColor = vc.selectedColor
        }
    }

}

-

override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){
    println("select color with index \(indexPath.row)")
    self.selectedColor = palette[indexPath.row]
    self.performSegueWithIdentifier("colorSelected", sender: self)
}

如果您感到困惑,请务必观看视频以获得有关如何连接 unwind segue 的有用解释。