Search code examples
swiftgetvaluepickerview

How to get the very first value from PickerView when it first pop up / when user not yet start any access


I try to use this method selectedRow(inComponent: 0), yet it doesn't work for me. Any way out to get the first/default value from picker when it is not active?

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return countries.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return countries[row].name
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
       country.text = countries[row].name //`country.text` is just textField
    }
}

Solution

  • Not a big deal-

    Just define your picker view as global and access the value for objectAtIndex(0)

    And write this line of code in viewDidLoad()

    Not exact, but something like this-

    @IBOutlet var yourPicker: UIPickerView! = UIPickerView()
    
    var yourArray = ["Apple", "Samsung", "Nokia"]
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        yourPicker.text = yourArray[0]
    }