更改所有 类 的所有视图控制器的背景颜色被调用(swift 4)

change background color of all view controllers if all classes are called (swift4)

当用户无特定顺序访问所有三个视图控制器时。我希望这个程序中的所有视图控制器都变成绿色。但前提是所有三个 类 都被访问过。我不知道这是 coredata 还是 userdefulat 问题。

import UIKit

class oneV: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

    }
}

class twoV: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

class threeV: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

UserDefaults 对此非常有用,在其 viewDidLoad 函数中为每个 UIViewController 保存一个标志。

然后将这三个标志合二为一,并在每个UIViewController中检查viewWillAppear

检查下面的代码。

// First create this extension to check on each value
public extension UIViewController {
    func isAllVistied() -> Bool {
        let a =  UserDefaults.standard.bool(forKey: "VC1") // Key used to save inside the viewController
        let b =  UserDefaults.standard.bool(forKey: "VC2")
        let c =  UserDefaults.standard.bool(forKey: "VC3")
        if a && b && c {
            return true
        } else {
            return false
        }
    }
}

用法: 在每个 UIViewController 中使用此代码:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        UserDefaults.standard.set(true, forKey: "VC1") //Key changes based on the current viewController used in example (VC1, VC2, VC3)
    }
    override func viewWillAppear(_ animated: Bool) {
        if self.isAllVistied() {
            view.backgroundColor = .green
        }
    }
}