简体   繁体   中英

How to get real size UIView with autolayout

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

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

[view setNeedsLayout];
[view layoutIfNeeded];

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 .

最简单的解决方案是仅在-viewDidAppear:运行该代码(运行自动-viewDidAppear:后)。

This is awesome.

If you want to get frame without using layoutsubviews method during autolayout usage, Use this one:

dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"View frame: %@", NSStringFromCGRect(view.frame));
    })

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

最好的时刻是在viewDidLayoutSubviews期间,因为它发生在viewDidAppear之前,因此您仍然可以在显示视图之前进行一些修改。

[view layoutIfNeed] save me.

Use this method to force the layout of subviews before drawing. Using the view that receives the message as the root view, this method lays out the view subtree starting at the root.

After invoke this method, I can get actual size of custom view in xib. Thanks a lot to @Allen and the author.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM