0

I am trying to create a pickerView with fixed labels for each component in the pickerView. I found this piece of code in StackOverflow.

var labelTexts = ["Months", "Weeks", "Days", "Hours", "Minutes"]

let labelWidth = itemPicker.frame.width / CGFloat(itemPicker.numberOfComponents)

for index in 0..<labelTexts.count {
    let label = UILabel(frame: CGRect(x: itemPicker.frame.origin.x + labelWidth * CGFloat(index), y: 0, width: labelWidth, height: 20))
    label.text = labelTexts[index]
    label.textAlignment = .center
    itemPicker.addSubview(label)
}

And it's working but as soon as I changed the width of the pickerView(at first it was as wide as the superview) the labels started to change their positioning. I want each label above each component exactly matching.

How can I fix that?

Edit: I found the issue.

Rather than doing that CGRect(x: itemPicker.frame.origin.x + labelWidth * CGFloat(index), ....))

I tried that CGRect(x: (itemPicker.frame.origin.x + labelWidth) * CGFloat(index), ...)) Notice the parantheses and it works..

Glatteisen
  • 163
  • 1
  • 3
  • 11
  • am I missing someting, when you do this `labelWidth * CGFloat(index)` label's shouldn't align in the first place anyways. removed the ` CGFloat(index)` – SpaceDust__ Jun 07 '17 at 04:11
  • Thank you for answer.Without the CGFloat(index) it's worse than before – Glatteisen Jun 07 '17 at 13:36

0 Answers0