可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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