我一直在努力安装一个 UIImageView
,它使用 Aspect Fill
显示可变宽度和高度的图像。单元格高度不适应 UIImageView
的新高度并保持它的高度。
View 的层次结构是这样的
- UITableViewCell
- UITableViewCell.ContentView
- UIImageView
- UITableViewCell.ContentView
我在 XCode 自动布局中尝试了这些场景:
- 将
UIImageView => 高度
设置为在构建时移除
- 将
UIImageView
的Intrinsic Value
设置为placeholder
- 将每个
UIImageView
、ContentView
和UITableViewCell
的Intrinsic Value
设置为placeholder
使用这些组合中的任何一个,我都会得到这样的 View :
http://i.stack.imgur.com/Cw7hS.png
蓝线代表单元格边框(boundaries),绿线代表UIImageView
边框(boundaries)。此示例中有四个单元格,第一个和第三个没有图像,第二个和第四个具有相同的图像(溢出没有图像的单元格)。
最佳答案
我根据之前的两个答案拼凑了一个解决方案:
- https://stackoverflow.com/a/26056737/3163338 (见第 1 点)
- 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
和 UIView-Encapsulated-Layout-Height
;但是,我学会了如何尊重它并接受它:)
只是将解决方案留在这里供任何人检查。这适用于 iOS 8。我尝试使用 iOS7,但它的工作方式与您需要实现 tableView:heightForRowAtIndexPath
根据其中包含的所有项目计算单元格的高度并禁用设置:
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44.0
关于ios - 使用 AutoLayout 在自定义 UITableViewCell 中使用 Aspect Fill 的 UIImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29062905/