I have the following setup in my storyboard in a Swift project:
I have an array containing many UIColor:
let palette = [UIColor.greenColor(), UIColor.redColor(), ...]
The user can click on the "Button" Tab bar button, and the second VC will be presented modally (vertical cover). From there he can choose a color from the collection view. The first VC is a UIViewController, the second is a UICollectionViewController. In the second VC I have the following code to handle color selection:
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)
}
How can I pass back the selected color to my first view controller? I tried:
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)
}
Above code gives me Unexpectedly found nil while unwrapping Optional value
It seems even when instantiating, backgroundView.backgroundColor is not available.
I also tried to execute the above code in the completion block of dismissViewController, with the same error:
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]
})
}
Thanks a lot for any suggestions, I am really loosing my head over this. Please let me know if anything is unclear, I will be happy to provide more information.