[英]aspect ratio for imageView in dynamic tableViewCell
I've got a tableView with 4 dynamic prototype cells: three of them for different kind of labels and one for an imageView. 我有一个带有4个动态原型单元格的tableView:三个用于不同类型的标签,一个用于imageView。
In viewDidLoad() I use this code to determine the height of each cell based on their content: 在viewDidLoad()中,我使用以下代码根据其内容确定每个单元格的高度:
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableViewAutomaticDimension
The problem is for the cell with the imageView. 问题在于带有imageView的单元格。 The picture to be displayed occupies almost all the cell and it needs to be shown in landscape keeping it's aspect ratio.
要显示的图片几乎占据了所有单元格,因此需要以横向显示,并保持其长宽比。 I was able to do it, setting top, bottom, trailing, leading and height constraints: in this way the tableView could calculate the appropriate row.height.
我能够做到这一点,设置顶部,底部,尾部,前导和高度约束:通过这种方式,tableView可以计算适当的row.height。
Switching from iPhone 6 to 4, the image width is reduced but the height remains the same resulting in strange ratios. 从iPhone 6切换到4,图像宽度减小,但高度保持不变,导致奇怪的比率。
I need to calculate the eight of the view based on the width of the moment and I tried it in two ways: 我需要根据瞬间的宽度来计算视图的八个视图,并通过两种方法进行了尝试:
creating an NSLayoutConstraint outlet for the height. 为高度创建一个NSLayoutConstraint出口。 If I assign it a static value it works but when I try to calculate like:
如果我给它分配一个静态值,它可以工作,但是当我尝试像这样计算时:
constraintOutletForTheHeight.constant = CGFloat(myImageView.frame.size.width / 2)
it starts showing the first cells with the old value and the others appear with the computed height value. 它开始显示第一个具有旧值的单元格,而其他单元格显示具有计算出的高度值。
I also attempted setting the aspectRatio constraint from Storyboard but in both cases Xcode tells me that it can't simultaneously satisfy constraints. 我还尝试从Storyboard设置AspectRatio约束,但是在两种情况下,Xcode都告诉我它不能同时满足约束。
Thank you for your interest 感谢您的关注
After a lot of println() I found where I was wrong and a solution for that (not the most elegant but at least it works). 经过大量的println()处理后,我发现了我的错误所在,并找到了解决方案(不是最优雅的方法,但至少可以解决)。
I discovered that the starting width of the imageView is the one assigned via storyboard (even after I set the imageView.image property) and after a bit of scrolling, it switches to presumed value: this is why I got constraint errors. 我发现imageView的起始宽度是通过情节提要分配的宽度(即使在设置了imageView.image属性之后),并且经过一点滚动后,它仍切换为假定值:这就是为什么我遇到约束错误的原因。 As a solution in tableView:cellForRowAtIndexPath:, I used the tableView width property like this:
作为tableView:cellForRowAtIndexPath:中的解决方案,我使用了tableView width属性,如下所示:
cell.<image_view_height_contraint>.constant = CGFloat(tableView.frame.size.width / 2)
If you know a better solution you're welcome otherwise I hope it could help someone else. 如果您知道更好的解决方案,我们将不欢迎您,否则我希望它可以对其他人有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.