Swift visual delay in text height change

时间:2015-05-24 20:47:34

标签: ios swift view autolayout

I have a main display with a button, and when that button is clicked, it transitions to a second screen. In that second screen, I have a text label with a colored background that changes depending on the size of the screen using auto layout / constraints.

I am then changing the size of the font in that label relative to the label size using:

LabelName.font = LabelName.text.fontWithSize(LabelName.frame.height)

it works, but there is an issue. When I put the above line in viewDidLoad, nothing happens...the text remains unchanged. When I put it in viewDidAppear, it changes, but for a brief moment the original text size shows on the label before changing.

The issue I'm having here is that when I segue onto that screen, I can see the label is always the correct, adjusted size (even during the segue). It enlarges itself based on the screen size just fine...so since that's always not delayed shouldn't the text size line not be delayed? I used some output lines and in viewDidAppear the frame for that label is the original size, and in viewDidAppear it is the size it should be without delay. Yet the text delays.

Only reason I can see is that the auto/layout constraints are adjusted after the view loads but before it appears, and the actual swift code in viewDidAppear is only performed after the view is done seguing and appears completely on the screen. But I'm not sure if this is true....

Clarification would be appreciated, and even a better way to adjust the text based on label size without direct code would be awesome. I don't see a simple "Adjust font size to label size" option in the attributes. Maybe there is and I just haven't picked up on it. Any way to do it before having to code it directly would be nice, but just a general workaround solution works. I just don't want to see that little bit of delay. It's not very smooth or pleasing to see.

1 个答案:

答案 0 :(得分:0)

Your theory is correct. Auto Layout lays out the views after ViewDidLoad() and you need this to be done before you can adjust your font. Move you font adjustment code to an override of viewDidLayoutSubviews() which happens after Auto Layout but before the view appears on screen.

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    LabelName.font = LabelName.text.fontWithSize(LabelName.frame.height)
}