简体   繁体   English

根据其他视图的颜色更改视图颜色

[英]Change View Color based on another View's Color

I have a simple iOS app written in Swift that chooses a random background color every time a button is pushed. 我有一个用Swift编写的简单iOS应用,每次按下按钮时都会选择随机的背景颜色。 There is a "Credits" button in the view that acts as a modal segue to another view. 视图中有一个“ Credits”按钮,可作为另一视图的模式选择。 How would I go about setting the color of the second view based on whatever color the background is in the first view? 如何根据第一个视图中的背景颜色设置第二个视图的颜色?

You need to pass color from first controller to second. 您需要将颜色从第一个控制器传递到第二个控制器。 below is the snippet. 以下是代码段。

 let destinationVC:ViewControllerClass = segue.destinationViewController as! ViewControllerClass
destinationVC.color = view.backgroundColor

You can archive this like this: 您可以这样归档:

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    if (segue.identifier == "Load View") {
        // pass data to next view
       let viewController:ViewController = segue!.destinationViewController as  ViewController
       viewController.view.backgroundColor = self.view.backgroundColor   
    }
}

You can pass some arguments to the view controller you're presenting or pushing by overriding prepareForSegue method : 您可以通过重写prepareForSegue方法将一些参数传递给您要显示或推送的视图控制器:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {        
     if let secondViewController = segue.destinationViewController as? MySecondViewControllerClass {
        secondViewController.view.backgroundColor = view.backgroundColor   
     }
}

You can find more infos available about prepareForSegue on UIViewController documentation from Apple. 您可以从Apple的UIViewController文档中找到有关prepareForSegue更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM