简体   繁体   English

UIView背景颜色不变吗?

[英]UIView Background Color Not Changing?

When I run my application, the background color does not adjust. 当我运行我的应用程序时,背景色不会调整。 Colornumber is a global variable. Colornumber是一个全局变量。 In AppDelegate.swift, it is initialized to have a value of 0. When the application is run, ViewWillAppear is called for the first time with a value of 0. It is called when the ViewController appears. 在AppDelegate.swift中,它初始化为具有0的值。运行应用程序时,第一次调用ViewWillAppear,其值为0。在出现ViewController时调用它。 Next, viewWillAppear is run again (because it is called in DidFinishLaunchingWithOptions) after the colorNumber variable has been changed to 2. The program enters the second condition (because it correctly prints out "We're in the second condition"). 接下来,将colorNumber变量更改为2后,再次运行viewWillAppear(因为在DidFinishLaunchingWithOptions中被调用)。程序进入第二个条件(因为它正确打印出“我们处于第二个条件”)。 However, the background color remains green. 但是,背景色仍为绿色。 How come the background color does not change to blue? 背景颜色为什么不变为蓝色? Thanks. 谢谢。

ViewController.swift: ViewController.swift:

var colorNumber: Int!

class ViewController: UIViewController {

    func setInitialColor() {
        if colorNumber! == 1 {
            self.view.backgroundColor = .green
            print("We're in the First Condition")
        }
        else if colorNumber! == 2 {
            self.view.backgroundColor = .blue
            print("We're in the second condition")
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        self.setInitialColor()
    }
}

AppDelegate.swift: AppDelegate.swift:

func application(_ application: UIApplication, 
didFinishLaunchingWithOptions launchOptions: 
[UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    colorNumber = 0
    colorNumber = 1
    ViewController().viewWillAppear(false)
}

You should never call lifeCycle methods yourself. 您永远不要自己调用lifeCycle方法。 So, instead of calling viewWillAppear() , you could call a method that sets a property or call setInitalColor() . 因此,您可以调用设置属性的方法或调用setInitalColor()而不是调用viewWillAppear() setInitalColor()

Your real issue is that you are creating a second instance of ViewController in this statement: 真正的问题是您要在此语句中创建ViewController的第二个实例:

ViewController().viewWillAppear(false)

That isn't the same ViewController that is on screen. 那与屏幕上的ViewController Instead, you could ask the window for its rootViewController and then call setInitialColor() on that: 相反,您可以向window询问其rootViewController ,然后在该window调用setInitialColor()

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    colorNumber = 2

    let vc = window?.rootViewController as? ViewController
    vc?.setInitialColor()  // color is now blue!

    return true
}

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

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