0

It seems like autolayout overrides commands in 'ViewDidLoad'.

Target : I want to define the size of a label programmatically to reflect the importance of my label. I DON'T want the label to fit the size of the text. I don't want neither the text of the label to fit the size of the label.

I code in Swift and Xcode 6.

When I use in 'ViewDidLoad'

        team1ScoreLabel.frame.size.width=400

it has no effect.

When I copy and paste it in a button action function, it resizes as I wish the size of the label. So the line of code is OK.

To me, it means autolayout constraints does not allow the label to be resize in 'ViewDidLoad' method. I have tried with no success in 'ViewDidAppear'

Any idea how to resize the label size when the view appears ? I don't want to disable autolayout because I'm using it a lot for other constraints.

GoldXApp
  • 2,397
  • 3
  • 17
  • 26
  • 1
    You can create an IBOutlet reference to the appropriate constraint(s) and the modify the constraints at runtime rather than trying to manipulate the frame. – Paulw11 Oct 24 '15 at 20:26

1 Answers1

2

You can't move views around by changing their frames when auto-layout is in effect. When any of the layout methods get called, the constraints on the views will move the views back based on their rules.

As PaulW11 says in his comment, you want to create constraints and connect them to IBOutlets and then change the values of the constraints in your code. Note that viewDidLoad is probably too soon, since at that point the view controller's content view hasn't been adjusted for the size and orientation of the screen. You probably want to do your adjustments in viewWillAppear.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • Creating an IBoutlet for the constraint was the right solution then I just had to detail the size as 'team1ScoreLabelWidth.constant=400' for instance. It even works in 'ViewDidLoad' method. Interesting page about it : http://stackoverflow.com/questions/22086054/unable-to-make-outlet-connection-to-a-constraint-in-ib – GoldXApp Oct 25 '15 at 12:49
  • 1
    Yes, it will work in `viewDidLoad` as long as your code doesn't do any math that relies on the current size of the content view or position/size of other views, since those are subject to change until layoutSubviews is done running. It's safer to put such code in `viewWillAppear`, since by then everything else is set up. Also, if you cover a view controller with another one (like a modal) and then come back, `viewWillAppear` gets called again, but `viewDidLoad` does not. – Duncan C Oct 25 '15 at 14:17