Search code examples
arraysswiftuipickerview

how to get user selection in UIPickerView and use it else where?


all i want to do is change the values of min avg and max based on what the user selected in the picker menu so that i can use them in the MinC AvgC and MaxC label calculation. for example, if user selected a1 then min = 10, avg = 15, and max = 20, but if user selects a2 i want min to = 20, avg = 25, and max = 30. please help and thank you. your time, effort, and support are appreciated. bellow is my code which is currently working without any errors:

class ViewController: UIViewController, UIPickerViewDelegate, UITextFieldDelegate{

    @IBOutlet var PLabel: UILabel!

    @IBOutlet weak var C: UITextField!

    @IBOutlet var MinC: UILabel!
    @IBOutlet var AvgC: UILabel!
    @IBOutlet var MaxC: UILabel!

    var min = 0
    var avg = 0
    var max = 0

    var P = ["a1","a2","a3","a4"]

    var CFiller = ["0"]

    override func viewDidLoad()
    {super.viewDidLoad()
     PLabel.text = P[0]
     MinC.text = CFiller[0]
     AvgC.text = CFiller[0]
     MaxC.text = CFiller[0]
     C.keyboardType = UIKeyboardType.NumberPad}


    override func didReceiveMemoryWarning()
    {super.didReceiveMemoryWarning()}

    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int
    { return 1}

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

    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
    {return P[row]}

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
    { var PSelected = P[row]
          PLabel.text = PSelected}





    @IBAction func CalcButton(sender: AnyObject)
        {if let ic = Int (C.text!)
        {MinC.text = "\(min * ic)"
         AvgC.text = "\(avg * ic)"
         MaxC.text = "\(max * ic)"}}

}

Solution

  • Seems to me like you just need to use a switch statement to achieve your goal.

    This could look something like this:

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
    { var PSelected = P[row]
    PLabel.text = PSelected
    
    switch PSelected {
    case "a1":
        min = 10
        avg = 15
        max = 20
    case "a2":
        min = 20
        avg = 25
        max = 30
        ...
    default:
        break
    }
    }
    

    You could also set it up more efficiently if you desire, like this:

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
    { var PSelected = P[row]
    PLabel.text = PSelected
    
    var increment = 10
    min = 10
    avg = 15
    max = 20
    
    min += increment*row //if a1, then row == 0, so nothing is added
    avg += increment*row
    max += increment*row
    
    }