Connect to ViewController from AppDelegate (Swift)

后端 未结 5 1166
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:12

    If you control-drag from the menu to the first responder (red cube above menu) and picked an existing action, then you can "responder chain" to your view controller. In my case I attached Open to openFile and then in my view controller I added the following

    override var acceptsFirstResponder: Bool {
        return true
    }
    
    func openFile(sender: NSMenuItem) {
        print("In view controller")
    }
    

    and it worked without any changes in AppDelegate. Most of the menus are already hooked up to first responder so just add the matching function name in your view controller.

    See this comment and this document on Event Handling Basics for more info.

提交回复
热议问题