Search code examples
iosnslayoutconstraintios-autolayout

How to find final value of proportional constraint


I have a constraint to set the height of the view.

The constraint is proportional height constraint.

I want to calculate the height using the constraint that's I want to know what is the view height.

any APIs to do that ?

I know I can manually find it myself as well using formula but I don't want to do that

Lets say the height constraint 58% of parent view and it has constant value of 10 then what is the total height assigned by constraint to the view


Solution

  • The height of the view will be:

    0.58 * parentView.frame.height + 10
    

    The height of the parentView isn't established until Auto Layout runs, so if you were to do this calculation, you would do it in an override of viewDidLayoutSubviews.

    Since you aren't interested in calculating that yourself, you can simply read the final frame height of the view in an override of viewDidLayoutSubviews which runs after Auto Layout has applied the constraints.

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
    
        // read final view size here
        print(myView.frame.height)
    }