Connect to ViewController from AppDelegate (Swift)

后端 未结 5 1168
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条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-04 16:24

    It seems that AppDelegate can connect to objects only within Application Scene in a storyboard. If you want to get a ViewController, instantiate it from a storyboard.

    sample:

    @IBAction func menuAction(sender: AnyObject) {
        if let storyboard = NSStoryboard(name: "Main", bundle: nil) {
            let controller = storyboard.instantiateControllerWithIdentifier("VC1") as NSViewController
    
            if let window = NSApplication.sharedApplication().mainWindow {
                window.contentViewController = controller // just swap
            }
        }
    }
    

提交回复
热议问题