我一直在努力适应UIImageView
显示可变宽度和高度的图像Aspect Fill
。单元高度不适应新的高度UIImageView
并坚持它的高度。
视图的层次结构是这样的
- UITableViewCell
- UITableViewCell.ContentView
我在 XCode 自动布局中尝试了这些场景:
- set the
UIImageView => Height
to remove at build time
- set the
Intrinsic Value
of the UIImageView
to placeholder
- set the
Intrinsic Value
对于每个UIImageView
, ContentView
and UITableViewCell
to placeholder
通过这些组合中的任何一个,我都会得到这样的视图:
https://i.stack.imgur.com/Cw7hS.png https://i.stack.imgur.com/Cw7hS.png
蓝线代表单元格边界(边界),绿线代表UIImageView
边界(边界)。此示例中有四个单元格,第一个和第三个单元格没有图像,第二个和第四个单元格具有相同的图像(溢出到没有图像的单元格上)。
我根据之前的两个答案拼凑了一个解决方案:
-
https://stackoverflow.com/a/26056737/3163338 https://stackoverflow.com/a/26056737/3163338(见第1点)
-
https://stackoverflow.com/a/25795758/3163338 https://stackoverflow.com/a/25795758/3163338(见第2点)
我想保留AspectRatio
无论其图像的Height
在修复的同时Width
根据该UIImageView
,图像的容器。
该解决方案包括:
-
添加新的AspectRatio
约束
let image = UIImage(ContentFromFile: "path/to/image")
let aspect = image.size.width / image.size.height
aspectConstraint = NSLayoutConstraint(item: cardMedia, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: cardMedia, attribute: NSLayoutAttribute.Height, multiplier: aspect, constant: 0.0)
添加此约束时,xCode 会抱怨新的“冗余”约束并尝试打破它,使其变得无用,但显示的图像与我想要的完全一样。这引出了第二个解决方案
-
将新约束的优先级降低到“999”似乎可以阻止 xcode 破坏它,并且它停止显示有关新约束的警告消息
aspectConstraint?.priority = 999
不知道为什么xCode会自动添加UIView-Encapsulated-Layout-Height
and UIView-Encapsulated-Layout-Height
在构建/运行时;然而,我学会了如何尊重这一点并接受它:)
只是将解决方案留在这里供任何人检查。这适用于 iOS 8。我尝试使用 iOS7,但它的工作方式与您需要实现的不同tableView:heightForRowAtIndexPath
根据单元格中包含的所有项目计算单元格的高度并禁用设置:
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44.0
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)