Search code examples
swiftuipickerview

Change select UiPickerView text based on a string


Hi I have a UIPickerView with strings inside, what I want is to select the text based on a string: I try to explain myself with a pseudo-language, what I would like to get is something like this:

if uipicker.gettext ()! = "mystring" {
    uipicker.selectext("mystring)
}

How can i do to get this in swift?


Solution

  • You most likely have an Array of strings to populate your picker, let say you have:

    let data = ["string 1", "string 2", "string 3"]
    

    You implement your UIPickerView something like this:

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return data.count
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return data[row]
    }
    

    Then you can create a method that for a given String selects row in the picker

    func selectPicker(withText text: String) {
        if let index = data.index(of: text) {
            picker.selectRow(index, inComponent: 0, animated: true)
        } else {
            print("text not found")
        }
    }
    

    And you are done :)