How to multiply number from a pickerview in swift

280 Views Asked by At

I checked on the internet but couldn't find the answer to my question. Sorry if it is somewhere that I didn't find.

SO I have a picker view with names and each name has a value. I would like to add these value in another calculation. Here is the code:

class ViewController: UIViewController, UIPickerViewDelegate,  UIPickerViewDataSource {

@IBOutlet var PickerPres: UIPickerView!
@IBOutlet var LabelPres: UILabel!

let PVpres:[(name: String, numb: Double)] = [("Blue",1), ("Red",2),   ("Green",3)]



func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {

    return 1

}

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

    return PVpres[row].name
}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return PVpres.count

}

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    LabelPres.text = PVpres[row].name

}

I have also

var color = Float (ColorTextField.text!)!
var item = Float (ItemTextField.text!)!
var source = Float (SourceTextField.text!)!

And I would like to add the numb assign to the item in pickerView to this calculation:

Total = color * PVpres[0].numb / item* source

But it didn't work

Thank you

JC

1

There are 1 best solutions below

1
On BEST ANSWER

to get the selected row from the picker you have to use the selectedRow(inComponent component: Int) method. also you should check if any row is actually selected. but this code assumes your calculation is based on a simple array index

let selectedRow = PickerPres.selectedRow(inComponent: 0)

//check if any row is actually selected. if nothing is selected it will be -1
if selectedRow != -1 {
    Total = (color * PVpres[selectedRow].numb) / item* source
}