NSPopUpButton selection to Float Swift 4

76 Views Asked by At

I am trying to get a String value to a Float value from a NSPopUpButton.

E.g. I have 3 number selections. 50, 20, 10. When the user selects one of the numbers I would like a calculation made into a Float value.

I know this may be something very simple but I am new and I can't find anything on Stackoverflow. Any help would be appreciated. Here is an example of the code I have.

@IBOutlet weak var userInput: NSTextField!
@IBOutlet weak var result: NSTextField!
@IBOutlet weak var userMenuSelection: NSPopUpButton!

override func viewDidLoad() {
    super.viewDidLoad()

    userMenuSelection.removeAllItems()
    userMenuSelection.addItems(withTitles: ["50", "20", "10"])
}

@IBAction func pushButtonforResult(_ sender: Any) {
    /* 
    Not sure how to take the selected userMenuSelection and multiply it by the users input to get my result in a float. 
    E.g. look below. This of course does not work because the menu items are strings. 
    */

    result.floatValue = userMenuSelection * userInput.floatValue
}

Hope this makes sense to what I am asking.

2

There are 2 best solutions below

7
Shehata Gamal On

You can try

let arr = ["50", "20", "10"]

//

@IBAction func pushButtonforResult(_ sender: NSPopUpButton) {
   let selectedValue = Float(arr[sender.selectedTag()])!
   Result.floatValue = selectedValue * userInput.floatValue

   // OR

    let selectedValue = Float(sender.selectedItem!.title)!
    result.floatValue = selectedValue * userInput.floatValue

}
0
OOPer On

As you see, your userMenuSelection has titles representing the Float values as String.

You can simply retrieve the selected title and convert it to Float:

@IBAction func pushButtonforResult(_ sender: Any) {
    var selectedValue = Float(userMenuSelection.titleOfSelectedItem ?? "0") ?? 0.0

    result.floatValue = selectedValue * userInput.floatValue
}