How to get real size UIView with autolayout

35,825

Solution 1

The simplest solution is to just run that code in -viewDidAppear: (after autolayout has been run).

Solution 2

Before your "getting real size code", insert the following code:

[view setNeedsLayout];
[view layoutIfNeeded];

Solution 3

Since everybody assumes the access is done via a UIViewController and not inside a UIView subclass, the answers don't prove really useful. The correct way to get the correct size of a UIView subclass is in layoutSubviews.

Solution 4

Seems like - (CGSize)systemLayoutSizeFittingSize:(CGSize)targetSize; is what you are looking for:

Return Value
The size of the view that satisfies the constraints it holds.

Discussion
Determines the best size of the view considering all constraints it holds and those of its subviews.

https://developer.apple.com/documentation/uikit/uiview/1622624-systemlayoutsizefittingsize?language=objc

Solution 5

You could just use the UIView method intrinsicContentSize

enter image description here

which you can read about https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/#//apple_ref/occ/instm/UIView/intrinsicContentSize

Share:
35,825
Chicken
Author by

Chicken

Updated on June 22, 2020

Comments

  • Chicken
    Chicken almost 4 years

    I'm a new developer iOS.

    I use auto-layout.

    I have a problem. I can not get real size of UIView after constraints.

    Example, when I want get size of UIView with constraint

    self.container.frame.size.height
    

    It alway return 550 for all device size. But I can see it have difference size when I run it on difference device.

    Thanks