问题
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:
- How can I add more than the 'three items' to this menu
- Whatever is selected in the popup, for that info to send an integer value to another number.
I very much would appreciate your help, Thanks.
回答1:
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.
来源:https://stackoverflow.com/questions/30421997/xcode-osx-swift-nspopupbutton