Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get View height based on margin constraints after runtime Swift

I have a circle in the centre of a screen with a margin constraint of 50 on either end. Hence, the width of the circle is dependent on the screen size.

So, what I tried was this:

Approach 1

I set up the margins in the storyboard to define the circle width (50 on left and right)

Then I used the following code:

@IBOutlet weak var helpButHeight: NSLayoutConstraint!
@IBOutlet weak var helpBut: UIButton!

ViewDidLoad:

helpButHeight.constant = helpBut.frame.size.width

This didn't work.

Since the screen width is 400, and the margin is 50 on either end, then helpBut.frame.size.width should have given me 300.

Instead it gave me 46.

Approach 2

This was my work-around:

ViewDidLoad:

    let screenSize: CGRect = UIScreen.mainScreen().bounds
    helpButHeight.constant = screenSize.width - 100

because 100 = 50 + 50, the two margins.

Works fine !

Question

Why did I have to do this? Why did the first approach not work? Why 46 and not 300?

like image 522
Greg Peckory Avatar asked Aug 26 '15 10:08

Greg Peckory


1 Answers

The reason is that constraints haven't kicked in, in the viewDidLoad function. The lifecycle looks something like

  • viewDidLoad -- Constraints haven't set
  • viewWillAppear -- Constraints haven't set
  • viewWillLayoutSubviews -- Constraints are setting
  • viewDidLayoutSubviews -- Constraints are set
  • viewDidAppear -- Constraints are set
like image 109
Shamas S Avatar answered Nov 09 '22 22:11

Shamas S