Reputation: 89
Lets say I have a Txt-File which should be read in with these 3 entries:
/dev/disk1s1
/dev/disk3s2
/dev/disk4s3
Every one of these 3 Entries should be "imported" as a Item into an existing NSPopUpButton. In my case this delegated one:
@IBOutlet weak var testmenu: NSPopUpButton!
What are the next steps to create a dynamic Menu from the 3 dev-Lines above?
@El Tomato Ok the Array is working. But don´t know how to add "drives" to the Outlet.
do {
let file = try String(contentsOfFile: "/tmp/drives")
let drives: [String] = file.components(separatedBy: "\n")
print(drives)
} catch {
Swift.print("Fatal Error: Couldn't read the contents!")
}
Upvotes: 2
Views: 1880
Reputation: 93161
It's pretty simple:
class ViewController: NSViewController {
@IBOutlet weak var popupButton: NSPopUpButton!
override func viewDidLoad() {
super.viewDidLoad()
popupButton.menu?.removeAllItems()
// You should get this from your file
let fileContent = """
/dev/disk1s1
/dev/disk3s2
/dev/disk4s3
"""
for (index, drive) in fileContent.components(separatedBy: "\n").enumerated() {
popupButton.menu?.addItem(withTitle: drive, action: #selector(ViewController.menuItemClicked(_:)), keyEquivalent: "\(index + 1)")
}
}
@objc func menuItemClicked(_ sender: NSMenuItem) {
print("\(sender.title) clicked")
}
}
The keyEquivalent
is the shortcut key for the menu item. If you don't want it, pass an empty string.
Upvotes: 3