简体   繁体   中英

Multiple UIPickerView select first row programmatically in Swift

I find same case for one pickerView , I will say same words like below:

I have a pickerView that pops up when a textField is clicked inside. The user selects their location in the pickerView , and it's put into the textField .

When opening the pickerView , the slider is on the first element, but if I click the done button to minimize the pickerView , that no element is selected (ie you must scroll down and back up to select the first element)

I can make for a textField and a pickerView . But I have 3 textFields and 3 pickerViews. Can I do for every pickerView ?

Below code block, works for one.

func textFieldDidBeginEditing(_ textField: UITextField) {
    if textField == yourTextField {
        self.yourPickerView.selectRow(0, inComponent: 0, animated: true)
        self.pickerView(yourPickerView, didSelectRow: 0, inComponent: 0)
    }
}

How you described in comment, you want to start editing textField when user click to specific textField if text of previous textField isn't empty. So use textFieldShouldBeginEditing delegate method like this:

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    if textField == textField1 {
        return true
    } else if textField == textField2 && !textField1.isEmpty {
        return true
    } else if textField == textField3 && !textField2.isEmpty {
        return true
    }
    return false
}

Then, when textField begin editing show specific pickerView

func textFieldDidBeginEditing(_ textField: UITextField) {
    if textField == textField1 {
        // show pickerView1
    } else if textField == textField2 {
        // show pickerView2
    } else if textField == textField3 {
        // show pickerView3
    }
}

and then when user select row you want to change text in textField

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    if pickerView == pickerView1 {
        textField1.text = items1[row]
    } else if pickerView == pickerView2 {
        textField2.text = items2[row]
    } else if pickerView == pickerView3 {
        textField3.text = items3[row]
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM