我在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]
})
}
非常感谢您的任何建议,我对此确实感到头疼。如果有任何不清楚的地方,请告诉我,我们将乐意提供更多信息。
最佳答案
This blog post包括完整的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)
}
如果您感到困惑,请务必观看视频,以获取有关如何连接放松序列的有用说明。