【发布时间】:2018-06-16 21:44:24
【问题描述】:
当我运行我的应用程序时,背景颜色没有调整。颜色编号是一个全局变量。在 AppDelegate.swift 中,它被初始化为值为 0。应用程序运行时,第一次调用 ViewWillAppear,值为 0。它在 ViewController 出现时调用。接下来,在 colorNumber 变量更改为 2 后再次运行 viewWillAppear(因为它在 DidFinishLaunchingWithOptions 中调用)。程序进入第二个条件(因为它正确打印出“我们处于第二个条件”)。但是,背景颜色保持绿色。为什么背景颜色不会变成蓝色?谢谢。
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)
}
【问题讨论】:
-
永远不要自己调用
viewWillAppear(或任何其他视图控制器生命周期方法)。时机成熟时会调用它。
标签: ios swift uiview view uibackgroundcolor