简体   繁体   中英

ios auto layout with dynamic size

I have a View inside my UIViewController , it has 4 constraints: Spaces from left, right and bottom are 0 and it has aspect radio. It looks like this:

 ______             _
|      |             \
|      |             |
|      |             |- ViewController
|      |             |
|______|             |
|______| <- View    _/

I want to insert in the center of the UIView an ImageView that has dynamic size, and I want it to stay in the center. I did this resizing in code but now I want to center it with Auto-Layout, but when I center horizontally and vertically it tells me I need more constraints for the size of the ImageView .

What should I do in order to the ImageView stay in center and the Auto-Layout don't complain about these missing size constraints?

From your question, I assume that you are setting this up in Interface Builder, correct me if I'm wrong.

Your problem is that at compile time the layout is not fully specified. A UIImageView has an intrinsic content size which would complete the layout, but because you don't set the image for the image view at that time it isn't yet specified.

You can set a placeholder size in the size inspector of the UIImageView . This has no effect at runtime but tells the compiler that there will be an intrinsic content size later.

Interface Builder中占位符固有内容的大小

A simple solution:

Just set an image for your image view in Interface Builder.
(You can use any image you like as a placeholder and change it at runtime through your code.)


Explanation:

The moment you assign a concrete image to a UIImageView it assumes an intrinsicContentSize that's equal to the image's size. This way it has a defined width and height and if you constrain its position (both x and y) then the layout is unambiguous and Interface Builder won't complain (that is if the rest of your layout is flawless).

If you don't want to use an image as a placeholder you'll have to manually set the image view's width and height for use in Interface Builder as described in iCaramba's answer .

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