在全宽 UIView 内水平对齐 UILabel 和 UIImageView

Horizontally align UILabel and UIImageView together inside of a full width UIView

我的布局中有一个 UIView 固定在 VC 的两侧。在里面我有一个图标 UIImageView 和旁边的 UILabel。我希望无论标签内的文本有多长,它们都在 UIView 内居中对齐。 (类似于您将如何使用 text-align:center; 在 CSS 中对齐图像和文本中心)。

|          UIView         |
|                         |
|                         |
|                         |
|     |image| |label|     |
|                         |
|                         |
|                         |
|                         |

有时标签可能很长,但我仍然需要它们居中:

|          UIView         |
|                         |
|                         |
|                         |
|  |img| |label is long|  |
|                         |
|                         |
|                         |
|                         |

我知道如何使用 Autolayout 但这个让我很困惑,因为我无法创建 "holder" UIView 并将其居中。我需要一些帮助来确定要在 IB 中添加的约束。

想法?

在主视图中创建一个新的 UIView 并将 UUImageViewUILabel 放入其中,此视图应具有以下约束

使用界面生成器

  1. 在主视图内水平对齐
  2. 在主视图内垂直对齐(与现在的 imageView 相同)

在视图控制器中使用代码

  1. width = image.width + label.width + horizo​​ntal space between imageView & label
  2. 高度 = 最大值 (image.height, label.height)

我想这很简单...使用情节提要...

如果您还没有找到解决方案...请查看此图片并按照...

这里...图像中的 UIView 为绿色背景

和我 select update constraintsresolve autolayout views

观看

基于@Mahmoud Adam 的回答,我们可以完全在故事板中完成此操作。

  1. 水平和垂直对齐 UIView 相对于其父视图。
  2. UIImageUILabel 添加约束,以便将它们固定到 UIView 的边缘。

UIView 会随着 UIImageUILabel 在里面长大。