Connect a menu item

(Swift 5, macOS, Xcode 11, Storyboards)


I try to connect a menu button. I have googled it intensely and I am confused as there is little updated information. I am new and I am confused.


What I have tried is to control drag from the menu button to the AppDelegate.swift and I have created an action. It works well if I print something. But I do not understand how can I make do something to an NSView or a label. For instance, in this example, I put a blue NSView in the storyboard and I try to fadeOut when I click button1 on the Menu. (In iOS I would put an outlet in the viewController.swift. But in macOS I suppose, it should be in the AppDelegate.swift? If I try to control drag from the NSView to the AppDelegate, it is not possible)


I put that in the AppDelegate.swift:

@IBActionfunc button1(_ sender: NSMenuItem) {
     
        print ("I click to button1 in the menu")
   
        // When I add that, I have an error: use of unresolved identifier 'nsView1'. 
        // I do not know how to connect nsView1 with the button, if the button is in the AppDelegate.swift)
        NSAnimationContext.runAnimationGroup({ (context) in
          context.duration = 2.0
            nsView1.animator().alphaValue = 0
    }

    }


I put that in the ViewController.swift:

overridefunc viewDidLoad() {
        super.viewDidLoad()
      
        nsView1.wantsLayer = true
        nsView1.layer!.backgroundColor = NSColor.blue.cgColor

    }


Where I should I put that and how to make the button recognize the nsView1 ?:

@IBOutletweakvar nsView1: NSView!

Accepted Reply

You have effectively to put the animation in the controller that holds the NSView.


A simple way to do this is to post a notification in

@IBAction func button1(_ sender: NSMenuItem) {


instead of calling animation


Then the Controller where view1 is has to subscribe to the notification (in its viewDidLoad)


And set the action on notification to an @objc func that calls the animation.

Replies

Menu button ? What is it ? Do you mean menu item ?


Have a look here if you are using storyboard, I've just answered a similar question (if I understand yours correctly).

https://forums.developer.apple.com/thread/125659

You have effectively to put the animation in the controller that holds the NSView.


A simple way to do this is to post a notification in

@IBAction func button1(_ sender: NSMenuItem) {


instead of calling animation


Then the Controller where view1 is has to subscribe to the notification (in its viewDidLoad)


And set the action on notification to an @objc func that calls the animation.

I see you've updated your OP. What additional info ?


Did you try with notification ? Does it work ?