ios - 使用 AutoLayout 在自定义 UITableViewCell 中使用 Aspect Fill 的 UIImageView

标签 ios uitableview swift autolayout

我一直在努力安装一个 UIImageView,它使用 Aspect Fill 显示可变宽度和高度的图像。单元格高度不适应 UIImageView 的新高度并保持它的高度。

View 的层次结构是这样的

  • UITableViewCell
    • UITableViewCell.ContentView
      • UIImageView

我在 XCode 自动布局中尝试了这些场景:

  • UIImageView => 高度设置为在构建时移除
  • UIImageViewIntrinsic Value 设置为 placeholder
  • 将每个 UIImageViewContentViewUITableViewCellIntrinsic Value 设置为 placeholder

使用这些组合中的任何一个,我都会得到这样的 View :

http://i.stack.imgur.com/Cw7hS.png

蓝线代表单元格边框(boundaries),绿线代表UIImageView 边框(boundaries)。此示例中有四个单元格,第一个和第三个没有图像,第二个和第四个具有相同的图像(溢出没有图像的单元格)。

最佳答案

我根据之前的两个答案拼凑了一个解决方案:

我想保留图像的 AspectRatio 而不管它的 Height 而根据 Width UIImageView,图片的容器。

解决方案包括:

  1. 添加新的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 会提示新的“冗余”约束并试图打破它,使它变得无用,但仍完全按照我想要的方式显示图像。这使我想到了第二个解决方案

    1. 将新约束的优先级降低到“999”似乎可以阻止 xcode 破坏它,并且它不再显示有关新约束的警告消息

      aspectConstraint?.priority = 999

不确定为什么 xCode 在构建/运行时自动添加 UIView-Encapsulated-Layout-HeightUIView-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/

相关文章:

ios - 如何为不同的 UTableView 部分使用不同的 segues 并传递数据

ios - ld : framework not found Pods_MyProject_MyProjectTests

ios - 带有 iOS 14 的 AppsFlyer

ios - UITableView 没有滚动

iphone - 在测试用户上安装应用

ios - 在 tableView :editActionsForRowAt: 中处理图像

ios - scrollViewDidScroll 在设置表偏移后被调用 "twice"

ios - UITableViewCell 的详细文本标签在滚动时消失

iphone - CAGradientLayer,不能很好地调整大小,旋转时撕裂

ios - 为 iOS 添加 Google_analytics 尝试了很多方法都不起作用?