Search code examples
iosswiftautolayoutuilabeluipickerview

Dynamically adjust UILabel x-value based on UIPicker location?


I have a UIPickerView that stretches to leading view and trailing view in autolayout in storyboards.

I would like to add a UILabel next to each section of the UIPickerView that stay a constant 10 px away from the picker section.

Right now I am attempting to do so programmatically like so:

    var hourXVal = pickerWidth - 330.0
    var minXVal = pickerWidth - 190.0
    var secXVal = pickerWidth - 50.0

    if(self.view.frame.width == 320)
    {
        hourXVal = pickerWidth - 250.0
        minXVal = pickerWidth - 140.0
        secXVal = pickerWidth - 35.0
    }

    else if(self.view.frame.width == 414)
    {
        hourXVal = pickerWidth - 330.0
        minXVal = pickerWidth - 190.0
        secXVal = pickerWidth - 50.0
    }
    let hourLabel = UILabel(frame: CGRect(x:hourXVal, y:88, width: 100, height:40))
    let minuteLabel = UILabel(frame: CGRect(x:minXVal, y:88, width: 100, height:40))
    let secondLabel = UILabel(frame: CGRect(x:secXVal, y:88, width: 100, height:40))

    hourLabel.text = "Hours"
    minuteLabel.text = "Minutes"
    secondLabel.text = "Sec"

    self.timePickerView.addSubview(hourLabel)
    self.timePickerView.addSubview(minuteLabel)
    self.timePickerView.addSubview(secondLabel)

However, the self.view.frame.width reports the same width for an iPhone SE and iPhone 6even though for the 6 UI appears as so (Whereas it looks fine on the SE and 5):

enter image description here

Is there a better way to do this? how?


Solution

  • What is probably happening is the when you call self.view.frame.width the correct view width has not yet been calculated. It could have the correct width for the iPhone 5/SE if that was used in Interface Builder. This can happen if you are calling code that needs the width in -viewDidLoad since the view is loaded, but its final size hasn't been calculated. Since you're working with frames, try setting it in viewWillLayoutSubviews or viewDidLayoutSubviews.