如何从另一个视图控制器中的变量获取值

How do I get a value from a variable in another View Controller

我正在尝试从 ViewController 中的 PrefsViewController 中的 4 个不同变量中获取值,但是当 PrefsViewController 被取消时,值会重置。

ViewController.swift

的片段
class ViewController: NSViewController, NSWindowDelegate { 
    
    var triesEnabled = false
    var minNumber = 0
    var maxNumber = 20
    var maxTries = 3
    
    @objc func applyPrefs() {
        let mainSB = NSStoryboard(name: "Main", bundle: nil)
        let prefsVC: PrefsViewController = mainSB.instantiateController(withIdentifier: "prefsViewController") as! PrefsViewController
        minNumber = prefsVC.prefsMinNum
        maxNumber = prefsVC.prefsMaxNum
        triesEnabled = prefsVC.prefsTriesEnabled
        maxTries = prefsVC.prefsMaxTries
        print("\(minNumber) \(maxNumber) \(triesEnabled) \(maxTries)") // here I can see that it has been reset to the default values
        resetGame(minRange: minNumber, maxRange: maxNumber, isTriesEnabled: triesEnabled, triesLimit: maxTries)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(applyPrefs), name: Notification.Name("notifyApplyPrefs"), object: nil )
        resetGame(minRange: minNumber, maxRange: maxNumber, isTriesEnabled: triesEnabled, triesLimit: maxTries)
    }
}

首选项片段ViewController

class PrefsViewController: NSViewController {
    
    var triesOn = false
    
    var prefsMinNum: Int = 0
    var prefsMaxNum: Int = 20
    var prefsTriesEnabled: Bool = false
    var prefsMaxTries: Int = 3
    
    @IBAction func closeButton(_ sender: Any) {
        if (!minNumTextField.stringValue.isInt || !maxNumTextField.stringValue.isInt || !triesTextField.stringValue.isInt) {
            let alert = NSAlert()
            alert.messageText = "Error"
            alert.informativeText = "You can only enter (whole) numbers in the text fields."
            alert.alertStyle = .warning
            alert.addButton(withTitle: "OK")
            alert.runModal()
            return
        }
        prefsMinNum = Int(minNumTextField.intValue)
        prefsMaxNum = Int(maxNumTextField.intValue)
        prefsTriesEnabled = triesOn
        prefsMaxTries = Int(minNumTextField.intValue)
        
        print("minNumTextField: \(prefsMinNum) maxNumTextField: \(prefsMaxNum) triesCheckBox: \(prefsTriesEnabled) triesTextField: \(prefsMaxTries)")
        NotificationCenter.default.post(name: Notification.Name("notifyApplyPrefs"), object: nil)
        self.dismiss(self)
    }
}

首选项视图显示为 sheet(我不知道这是否重要)

当您使用 instantiateController 时,您正在创建一个新的、以前从未使用过的控制器实例。如果您想使用通知传输数据,请在调用 post 时将 self 作为对象发送,然后使用它来获取变量。

您还需要更改 applyPrefs 以便它采用 Notification 参数以便您可以使用通知对象。