Connect to ViewController from AppDelegate (Swift)

后端 未结 5 1170
Happy的楠姐
Happy的楠姐 2021-02-04 15:55

I have created a new OS X Cocoa Application using the standard Xcode Swift template (using StoryBoards).

I have implemented an IBAction in AppDelegate.swift to handle wh

5条回答
  •  梦毁少年i
    2021-02-04 16:12

    You can access the mainWinow property and the contentViewController property to create a reference to your custom ViewController class. This is similar to the iOS rootViewController property.

    let rootViewController = NSApplication.shared().mainWindow?.windowController?.contentViewController as! ViewController
    

    Now you can use this reference to access IBOutlets on your main storyboard from your AppDelegate.

    rootViewController.myTextView.textStorage?.mutableString.setString("Cats and dogs.")
    

    This is good for a simple app with one Window with one ViewController.

提交回复
热议问题