maplecobra
maplecobra

Reputation: 61

Xcode_OSX/Swift_NSPopUpButton.

I am incredibly new to this, so please keep that in mind!

I've been at this all night, watched countless videos/haunted countless forums...I can't find one single answer!

I am trying to make a basic popup menu in Swift/OSX What I need to figure out is:

I very much would appreciate your help, Thanks.

Upvotes: 5

Views: 4606

Answers (1)

Warren Burton
Warren Burton

Reputation: 17372

A NSPopupButton is a container for a bunch of NSMenuItem objects so to add an item you can use

func addItemWithTitle(_ title: String!)

The NSMenuItem gets constructed for you by the call.

and as you may wish to start from scratch you can use

func removeAllItems()

To clean existing items from the button.

There are also other methods around moving and removing menu items from the button.

A NSPopupButton is-a NSControl so you can use var action: Selector to set the action sent when an item is selected and var target: AnyObject! to control which object receives the message. Or just wire it up in Interface Builder.

protocol FooViewDelegate{
    func itemWithIndexWasSelected(value:Int)
}

class FooViewController: NSViewController  {

    @IBOutlet weak var myPopupButton: NSPopUpButton!
    var delegate: FooViewDelegate?

    let allTheThings = ["Mother", "Custard", "Axe", "Cactus"]

    override func viewDidLoad() {
        super.viewDidLoad()
        buildMyButton()
    }

    func buildMyButton() {
        myPopupButton.removeAllItems()

        myPopupButton.addItemsWithTitles(allTheThings)
        myPopupButton.target = self
        myPopupButton.action = "myPopUpButtonWasSelected:"

    }

    @IBAction func myPopUpButtonWasSelected(sender:AnyObject) {

        if let menuItem = sender as? NSMenuItem, mindex = find(allTheThings, menuItem.title) {
            self.delegate?.itemWithIndexWasSelected(mindex)
        }
    }


}

All the button construction can be done in Interface Builder rather than code too. Remember that you can duplicate items with CMD-D or you can drag new NSMenuItem objects into the button.

Upvotes: 10

Related Questions