Search code examples
iosswiftuipickerview

How can I implement multiple UIPickerView in a single page?


I am implementing UIPickerView in a text field as below:

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

public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return states.count // states is an array of strings
}

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

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    textField.text = states[row]
    self.view.endEditing(false)
}

I want to have another textfield that implement UIPickerView. How should I do it? Can I alter the methods implemented above to include both text fields?


Solution

  • Easily you can set to each pickerView a tag value, for example:

    let firstPV = UIPickerView()
    pickerV.tag = 1
    
    let secondPV = UIPickerView()
    secondPV.tag = 2
    

    In this way, just you have to evaluate the tag property in the PickerView' protocols, like:

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
    
        switch pickerView.tag {
            case 1:
                return 1
            case 2:
                return 3
        default:
            return 0
        }
    }