gpt4 book ai didi

Swift:解除模态呈现的 UICollectionViewController,传递数据

转载 作者:行者123 更新时间:2023-11-30 10:18:57 25 4
gpt4 key购买 nike

我在 Swift 项目的 Storyboard 中进行了以下设置:

enter image description here

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

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

用户可以点击“Button”选项卡栏按钮,第二个VC将以模态方式呈现(垂直覆盖)。从那里他可以从 Collection View 中选择一种颜色。第一个 VC 是 UIViewController,第二个 VC 是 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)
}

如何将所选颜色传回我的第一个 View Controller ?我尝试过:

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)
}

上面的代码给了我在展开可选值时意外发现nil

似乎即使在实例化时,backgroundView.backgroundColor也不可用。

我也尝试在dismissViewController的完成 block 中执行上面的代码,出现同样的错误:

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)
}

如果您感到困惑,请务必观看视频,获取有关如何连接展开转场的有用说明。

关于Swift:解除模态呈现的 UICollectionViewController,传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28406425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com