How to pass data from NSWindowController to its NSViewController?

匿名 (未验证) 提交于 2019-12-03 01:20:02

问题:

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

class MainWindowController: NSWindowController {      @IBOutlet weak var myButton: NSButton!      // ... } 

I have a class MainViewController that is that content NSViewController of the main window.

How can I access this button in my content NSViewController? Is there a better way to organize the IBOutlets and the controllers to facilitate this access?

回答1:

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     }  } 


回答2:

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 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!