Home > Enterprise >  Swift: How to hook up "Pop Up Button" event handler on selection update?
Swift: How to hook up "Pop Up Button" event handler on selection update?

Time:11-14

Hello I added a "Pop Up Button" from XCode Object Library, and wanted to hook it up with event handler that handles menu item selection update (for app's language selection).

The button is already created in *.xib file, and what kind of function should I create to hook up with button events?

I created a IBAction handler like this:

@IBOutlet weak var languageSettingButton: UIButton!

@IBAction func onLanguageSelected() {
    // handling selection
    // ...
}

But dragging the selector to this IBAction function did not work. What kind of selector function is it expecting? How do I hook it up?

Thanks!

My usage with two menu options regarding two app languages:

enter image description here

The Pop Up Button:

enter image description here

Update:

Followed @Charles Srstka's comment:

The IBAction func needs to have a sender param:

@IBAction func onLanguageSelected(_ sender: Any?) {
    
}

However the interesting thing is, we are able to hook up the entire button with the IBAction func, but not the menu item's selector, what should we do with the selector here? does it need to be hooked up with a function too?

enter image description here

CodePudding user response:

As your screen shot shows, the menu item has a Sent Action. Hook its selector to an IBAction function. Done.

It's difficult to know what you're doing wrong, because you have not given enough information in your question, and there are a thousand ways to do something wrong and just one way to do it right. But if you do it right, it works fine:

enter image description here

Here's the receiving code:

@IBOutlet var menuButton : UIButton!

@IBAction func doMenu (_ sender:Any) {
    print(menuButton.currentTitle)
}

And as you can see, my menu item is hooked to that action:

enter image description here

CodePudding user response:

Finally figured out the solution:

  1. Based on Charle's comment, in view controller file, add a selection handler with sender param:

    @IBAction func onSelectionUpdate(_ sender: Any?) {

    // add logic here
    

    }

  2. In the pop up button's menu item's selector hook, drag it all the way to "File's owner", after dragging, a small menu will show available IBAction functions, choose the one we just created.

Dragging to File's owner

IBAction function list shows up

  • Related