简体   繁体   中英

autolayout aspect ratio imageview in tableviewcell

I have a custom tableViewCell with an imageView inside it. Layout as such:

布局

I want to use autolayout to calculate height of the cell in method

CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];

so I set up constraints like this

树

Basically these constraints just pin each element to the edge of its superView or to the view above/below.

The problem is that there is one more constraint I want to add which is the imageView's aspect ratio. I want set imageView's height is always half of its width. If I directly set up aspect ratio constraint to 2:1 I always get Unable to simultaneously satisfy constraints error. I tried change the priority to high and still no luck.

Can I achieve this by using autolayout?

The reason why your constraints work and the automatic height is correctly calculated is that all the UI elements have their own intrinsic size (the size that would make it fit their content).

Therefore, the imageView already has a size to fit the image you put inside. You can't both use the intrinsic size and specify your own (even if you just want to change one of the dimensions).

A solution I see would be to have a static height constraint on your UIImageView , plus the aspect ration one for the width. Then in the code you set the constant for the height constraint to the image.size.height value.

[self.imageHeightConstraint setConstant:self.imageView.image.size.height];
[self.view layoutIfNeeded];

In this way you sort of keep half the intrinsic size (just the height) and get custom width.

Hope my explanation made sense 😊. Let me know if you have questions though.

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