1

I have a UIPickerView and a UILabel, separate from each other.

When the user selects a row in the UIPickerView, I change the UILabel text using the delegate function:

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
    label.text = String(row);
}

Yet for some reason changing the label's text causes the UIPickerView to jump back to the top (first row).

When I remove the line "label.text = String(row);" the UIPickerView does not jump at all.

This is very strange and I can't find any correlation between the two elements.

Thank you in advance for any replies :)

  • Does the label text get set correctly before it jumps back or does it become 0 every time? – Jason Mar 02 '17 at 00:12
  • Yes the text gets set correctly, and then the UIPicker jumps back –  Mar 02 '17 at 00:13
  • What if instead of setting the label text, you just print String(row)? Does it still jump? I've never seen this and don't have an answer so I'm trying to help you debug – Jason Mar 02 '17 at 00:15
  • Haha me neither it is so strange. Printing the string instead of setting the text works (no jump), I've tried commenting out different sections and it only happens when I set this label's text. –  Mar 02 '17 at 00:18
  • If I always set the text to "0", it jumps once and then works properly after that. –  Mar 02 '17 at 00:21
  • What if instead of a label you have a textfield with user interaction disabled? This won't get to the root of the issue but it might be a workaround for now – Jason Mar 02 '17 at 00:22
  • That works! Thank you very much. But then, I made a new label and tried it on that, and it worked! Then I tried changing the text on the original label, and it still jumped. The only difference between the new label and old label is that the old label was positioned using constraints, and the new label was positioned with x and y coordinates. I removed the constraints from the old label, and now it works! Strange, strange bug. I'll post a proper answer to this later on... –  Mar 02 '17 at 00:33
  • Were the label constraints aligned with the picker view (e.g. aligned vertical centers)? – Jason Mar 02 '17 at 17:51

1 Answers1

0

Turns out that this "strange magical bug" was due to the fact that I set the UIPickerViews's default value in viewDidLayoutSubviews() due to another bug.

Therefore whenever an element was changed, viewDidLayoutSubviews() was called and the UIPickerView's value was set again, causing it to jump.