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..