【问题标题】:Image not fit to imageview in custom tableview cell图像不适合自定义表格视图单元格中的图像视图
【发布时间】:2016-03-02 04:57:24
【问题描述】:

我正在尝试将图像加载到我的 tableview 单元格,但是,图像似乎比 imageview 大并且超出了 imageview 的边界。 我尝试将UIImageViewcontentMode 属性设置为ScaleAspectFit,但这并没有解决我的问题。

代码:

cell.imageView?.contentMode = UIViewContentMode.Center
cell.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
switch (post.priorityLevel){
    case "High Priority Posting":
        cell.imageView?.image = UIImage(named: "High Priority Posting")
    case "Priority Posting":
        cell.imageView?.image = UIImage(named: "Priority Posting")
    case "General Posting":
        cell.imageView?.image = UIImage(named: "General Posting")
    default:
        print("Priority Level can't be loaded to table")
}

我从界面生成器添加了我的表格视图的屏幕截图以及模拟器上的结果。

任何建议将不胜感激。

【问题讨论】:

  • 您可以在 UI 调试中检查图像大小,也可以检查所有约束。如果您能告诉我们您为单元设置了哪些限制条件,那么我们一定可以为您提供帮助。

标签: ios swift uitableview uiimageview


【解决方案1】:

遵循以下约束,您将看到自动布局的魔力

ImageView 约束:

为imageView设置要显示的固定高度和宽度,并设置VerticalCentre约束。将 imageView 的内容模式设置为 Aspect Fit。

顶部标签约束:

Label TrailingSpace 约束不应是一个常数值,而是将其设置为标准间距(即 8 pts)。

第二个标签约束:

Labels TrailingSpace 和 BottomSpace 约束不应为常数值,而是将其设置为标准间距(即 8 pts),并将其 VerticalContentHugging 优先级设置为 250

更新:

ImageView 对单元格的垂直约束:

Label1 TrailingSpace 到标准间距的单元格:

Label2 TrailingSpace 到标准间距的单元格,BottomSpace 到标准间距的单元格。

【讨论】:

  • 嗨,巴拉特,我喜欢你的回答,但你能告诉我在哪里添加verticalCentre约束和标签尾随空格吗?在任何地方都找不到它们
  • 非常感谢您的更新!!,这可能是我在 * 上收到的最好的答案
【解决方案2】:

试试 cell.imageView?.contentMode = UIViewContentMode.ScaleAspectFill

【讨论】:

  • 所以你的设计可能有问题。
【解决方案3】:

https://developer.apple.com/library/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson7.html#//apple_ref/doc/uid/TP40015214-CH8-SW1

在这个官方教程中,他们设计了一个和你一模一样的 tableview。我认为您的主要问题与缺乏约束/自动布局有关

【讨论】:

  • 是的,这就是我所遵循的确切 tut,我几乎每一步都遵循,但他们没有在 tut 中提到约束或自动布局
【解决方案4】:

UIImage

1)首先你设置imageview前导空间,等高,垂直居中到容器 2)自行设置高度

城市和州

1) 设置水平空间和 Top 为 UiimageView,Trailing 空间为容器视图 2)自行设置高度

描述标签

1)设置水平空间和底部为UiimageView,拖尾空间为容器视图

2) 自行设置高度 故事板 -> 设置线条 = 0

【讨论】:

    【解决方案5】:

    如果它是自定义表格视图单元格,请勿将 imageView 出口命名为“imageView”,将其命名为其他任何名称,例如:“cellImageView”。然后尝试将单元格 cellImageView 的 clipsToBound 设置为 true。

    【讨论】: