I have a ViewController with a UIScrollView on it. On this VC I programatically adjust the frame of a UILabel which is inside the scroll view. This is done on viewDidLoad. This UILabel comes from the VC's xib file, it is not created programatically, only its frame changed.
When I transition from this VC to another, then back, the UILabel's frame gets reset to the XIB's state. It's text however is not reset, it stays the same text I set before.
My investigation tells me that this occur on layoutSubviews, as the UILabel's properties are correct on willLayoutSubviews, then reset on didLayoutSubviews when moving back to the VC.
Is this expected behaviour? Is there a reason why the label's text remains but the frame gets reset? Is this because the UIScrollView calls layoutSubviews on its parent view whenever scrolling?
Thanks
I see two problems in your description. First, you said this:
On this VC I programatically adjust the frame of a UILabel which is inside the scroll view. This is done on viewDidLoad.
It is generally a bad idea to modify view frames in viewDidLoad
, because the system's layout phase (during which layoutSubviews
messages are sent) hasn't happened yet. In viewDidLoad
, your view's frame hasn't been adjusted for the current device's screen size and interface orientation yet.
Second, you said that you're using autolayout. The autolayout system sets the frames of views during the layout phase. The layout phase can be triggered by many different events, including (as you've discovered) the appearance and disappearance of views.
In order to make your adjustment to the label's frame “stick”, you need to modify the constraints that control the label's frame. One way to do this is to create an outlet of type NSLayoutConstraint
on your view controller for each constraint that you need to modify, and connect these outlets to the constraints in your xib. Then in your view controller's viewWillLayoutSubviews
, you can modify the constant
property of each constraint as necessary. (Ironically, constant
is the only modifiable property of an NSLayoutConstraint
.)