How to pass data from NSWindowController to its NSViewController?

前端 未结 2 525
猫巷女王i
猫巷女王i 2020-12-15 08:22

I have a IBOutlet of a NSToolBar button in my NSWindowController class, which is my main window class:

class MainWindo         


        
相关标签:
2条回答
  • 2020-12-15 08:54

    How about like this using delegate? This example will change your button's title.

    @objc protocol SomeDelegate {
        func changeTitle(title: String)
    }
    
    class ViewController: NSViewController {
    
        weak var delegate: SomeDelegate?
    
        @IBAction func myAction(sender: AnyObject) {
            delegate?.changeTitle("NewTitle")
        }
    
    }
    
    class MainWindowController: NSWindowController, SomeDelegate {
    
        @IBOutlet weak var myButton: NSButton!
    
        override func windowDidLoad() {
            super.windowDidLoad()
    
            // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
            let myVc = window!.contentViewController as! ViewController
            myVc.delegate = self
    
        }
    
        func changeTitle(title: String) {
            myButton.title = title
        }
    
    }
    
    0 讨论(0)
  • 2020-12-15 08:59

    To access NSViewController from NSWindowController:

    let viewController:MainViewController = self.window!.contentViewController as! MainViewController
    

    To access NSWindowController from NSViewController:

    let windowController:MainWindowController = self.view.window?.windowController as! MainWindowController
    
    0 讨论(0)
提交回复
热议问题