Search code examples
swiftuipickerview

Storing UIPickerView selection into a variable


How can I store UIPickerView selection into a variable?

func pickerView(pickerView: AKPickerView, didSelectItem item: Int) {
}

let selected = pickerView(samplePickerView, what goes here?)  

Solution

  • First of all you will be holding an array I guess. So let us name it pickerarray and be it a string array.

    func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int){
       selected = pickerarray[row] // selected is the variable
    }
    

    Here you are using the row property of pickerview.

    Edit For your clarification I am entering the whole code

    import UIKit
    
    
    class ViewController: UIViewController,  UIPickerViewDataSource,UIPickerViewDelegate {
    
    @IBOutlet var MyPickerView: UIPickerView!
    var selected = ""
    let words: NSArray = ["Cat", "Chicken", "fish", "Dog",
        "Mouse", "Guinea Pig", "monkey"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        MyPickerView.delegate = self
        MyPickerView.dataSource = self
    
        selected = words[0] // setting the default value
    
    }
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return words.count
    }
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return "\(words[row])"
    }
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        selected = words[row] as! String
    }
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 1
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
     }
    }
    

    to access the selected value from pickerview from any function, use

    let selectedvalue = selected