使用自动布局在 UIView 内水平居中 UILabel + UIImageView

Horizontally Center UILabel + UIImageView inside UIView with Autolayout

第一个问题:

我有 UIView,其中包含 UILabel(动态文本)+ UIImage。我希望它们在 UIView 内居中。就像这些图片一样:

答案 here 已过时,现在我们有了堆栈视图,也许它可以使任务更容易。

第二题:

我有三个彼此相邻的 UIView,每个都有 UIImageView + UILabel,它们应该在它们的容器中居中(问题 1)。在屏幕宽度较小的 iPhone 4 岁时,文本会破坏布局,如下图所示:

我用的是Xcode7.0 |目标 iOS8 及以上 | Swift2

清除包含并重新添加。我在 Xcode 7.0 中遇到了这个问题,但它显然已在 Xcode 7.0.1.

中修复

这实际上很容易在纯 Autolayout/IB 中完成,无需代码。它最终看起来像这样:

这是带有视图的故事板文件,因此您可以轻松查看约束。它使用相同的子视图包装器技术,但是根据需要将标签设置为 shrink/cut 的技巧是在包装器视图的两侧添加 >= 0 约束,以防止其扩展超过父视图的边界,这反过来又阻止了标签的增长。

https://www.dropbox.com/s/ml67zdjwugf8jco/SO_Solution-20151013.storyboard?dl=0

  1. Use Button (instead using ImageView & Label) and set appropriate image & title.
  2. set Image & Title Insets
  3. Add To View and Assign leading space & bottom space of superview constraint to first button
  4. Assign trailing space & bottom space of superview constraint to third button
  5. Assign Left Horizontal space (with first button) & Right Horizontal space (with third button) to second button.
  6. Add equal Width & fixed Height constraint with all three buttons.

also, you can add width constraint and make it with dynamic width.

In sort, you can complete it with button.