简体   繁体   English

tableviewcell中的自动布局纵横比imageview

[英]autolayout aspect ratio imageview in tableviewcell

I have a custom tableViewCell with an imageView inside it. 我有一个自定义tableViewCell,其中有一个imageView。 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. 基本上,这些约束只是将每个元素固定到其superView的边缘或上方/下方的视图。

The problem is that there is one more constraint I want to add which is the imageView's aspect ratio. 问题是我还要添加一个约束,即imageView的宽高比。 I want set imageView's height is always half of its width. 我想设置imageView的高度始终是其宽度的一半。 If I directly set up aspect ratio constraint to 2:1 I always get Unable to simultaneously satisfy constraints error. 如果我将宽高比约束直接设置为2:1,则总是会Unable to simultaneously satisfy constraints错误。 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). 您的约束起作用并正确计算自动高度的原因是,所有UI元素都有其自身的固有大小(使之适合其内容的大小)。

Therefore, the imageView already has a size to fit the image you put inside. 因此, imageView已经具有适合放入您的图像的大小。 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. 我看到的解决方案是在UIImageView上设置静态高度限制,再加上宽度的宽高比。 Then in the code you set the constant for the height constraint to the image.size.height value. 然后,在代码中将高度约束的常量设置为image.size.height值。

[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. 让我知道您是否有任何疑问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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