Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default value of UIPickerView when UITextField is touched

I want to keep the same placeholder text in my UITextField which is "Location". Once the UITextField is touched then I want the first value of the UIPickerView to be displayed. The way it is now the user has to scroll down then back up for the value to be displayed in the UITextField. I want the value to be displayed in the UITextField as soon as the UIPickerView is open. unselected, selected-UITextField still shows no value

override func viewDidLoad() {
    let thePicker = UIPickerView()
    thePicker.delegate = self
    location.inputView = thePicker
    thePicker.selectRow(1, inComponent: 0, animated: true)
}

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

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

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


func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    location.text = pickOptions[row]
}
like image 373
iOSHG Avatar asked Oct 27 '25 20:10

iOSHG


1 Answers

Implement the textFieldDidBeginEditing text field delegate method and set the text field's text if it doesn't already have a value.

func textFieldDidBeginEditing(_ textField: UITextField) {
    if textField.text!.isEmpty {
        // set the text as needed
    }
}
like image 184
rmaddy Avatar answered Oct 30 '25 11:10

rmaddy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!