【发布时间】:2015-02-09 09:27:29
【问题描述】:
我在 Swift 项目的情节提要中有以下设置:
我有一个包含许多 UIColor 的数组:
let palette = [UIColor.greenColor(), UIColor.redColor(), ...]
用户可以点击“按钮”标签栏按钮,第二个VC会模态呈现(垂直封面)。从那里他可以从集合视图中选择一种颜色。第一个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的完成块中执行上面的代码,还是一样的错误:
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]
})
}
非常感谢您的任何建议,我真的对此感到困惑。如果有任何不清楚的地方请告诉我,我很乐意提供更多信息。
【问题讨论】:
-
instantiateViewControllerWithIdentifier将创建一个新FirstViewController。你需要一个你已经拥有的参考。 -
嗨亚伦,感谢您的评论。我是否必须实现委托才能引用 FirstViewController?我找到了另一个问题的答案:stackoverflow.com/a/25204814/3778854 - 见第二点。这会是解决我的问题的有效方法吗?如果没有,你能告诉我更多关于如何在我的情况下实现这一点吗?无论如何,今晚我会试试这个 - 再次感谢!
标签: swift uiviewcontroller uicollectionview