Search code examples
swiftuipickerview

Pickerview lag when updating labels


I'm using a picker view, and want to update stuff on the screen relating to the item that is currently selected.

Here's the code from the program:

   func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    TeamLabel.text = teams [row]
    attackField.text = "\(attacks [row])"
    defenseField.text = "\(defenses [row])"
    currentRow = row
    return teams [row]
}

This puts the team name, attack and defense values on the screen.

However, when scrolling the picker, I get the wrong result a lot. The text output doesn't match what's currently in the picker. Any idea how I can fix this?

Thanks.


Solution

  • You are using the wrong delegate method to update your text fields (or labels).

    Update titleForRow to just:

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

    Then implement the didSelectRow delegate method to update your fields:

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        TeamLabel.text = teams[row]
        attackField.text = "\(attacks[row])"
        defenseField.text = "\(defenses[row])"
    }