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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With