触摸 UITextField 时设置 UIPickerView 的默认值

iOS*_*SHG 4 uipickerview ios swift

我想在我的 UITextField 中保留相同的占位符文本,即“位置”。触摸 UITextField 后,我希望显示 UIPickerView 的第一个值。现在的方式是用户必须向下滚动然后再向上滚动以在 UITextField 中显示值。我希望在 UIPickerView 打开后立即在 UITextField 中显示该值。 未选中, 选中的 UITextField 仍不显示任何值

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]
}
Run Code Online (Sandbox Code Playgroud)

rma*_*ddy 6

实现textFieldDidBeginEditing文本字段委托方法并设置文本字段的文本(如果它还没有值)。

func textFieldDidBeginEditing(_ textField: UITextField) {
    if textField.text!.isEmpty {
        // set the text as needed
    }
}
Run Code Online (Sandbox Code Playgroud)