Amir_P Amir_P - 4 months ago 46
Swift Question

Weird graphical issue with UIPickerView

I tried to put a

in a
and show a simple items in it with this code:

func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 3

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return 10

func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
let pickerLabel = UILabel()
pickerLabel.textColor =
pickerLabel.text = "10"
pickerLabel.textAlignment =
return pickerLabel

everything is fine but when I changed
to 2 picker view didn't show correct. Why this is happening?(Xcode 8 iOS 10)
with 2 component
with 3 component


There are two things to notice here:

  1. You have used: pickerLabel.sizeToFit() which would size the label to its content.
  2. Next is that if you comment pickerLabel.sizeToFit() and put a background color to your label. You'd get the following result

enter image description here

As you can see in here that PickerView has a curvature and a distance in between cells which is causing this issue. So solution is you can give a width to your label & no size to fit and apply a background while testing your result and come to the best possible combination.

For instance, check the iOS Native clock timer:

enter image description here

"They have tried playing around with width of label and index"

Please note:

The curvature is causing the width to decrease and label is center aligned so it is taking it along the path of decreasing width, if you get what i'm trying to say here.

This should explain it.