When I run my application, the background color does not adjust. Colornumber is a global variable. 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. 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"). However, the background color remains green. How come the background color does not change to blue? Thanks.
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:
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions:
[UIApplicationLaunchOptionsKey: Any]?) -> Bool {
colorNumber = 0
colorNumber = 1
ViewController().viewWillAppear(false)
}
You should never call lifeCycle methods yourself. So, instead of calling viewWillAppear()
, you could call a method that sets a property or call setInitalColor()
.
Your real issue is that you are creating a second instance of ViewController
in this statement:
ViewController().viewWillAppear(false)
That isn't the same ViewController
that is on screen. Instead, you could ask the window
for its rootViewController
and then call setInitialColor()
on that:
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
}