我在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]
})
}
非常感谢任何建议,我真的对此感到失望。如果有任何不清楚的地方,请告诉我,我很乐意提供更多信息。
答案 0 :(得分:1)
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)
}
如果您感到困惑,请务必观看视频,以获取有关如何连接展开赛段的有用说明。