Search code examples
iosautolayoutinterface-builderswift2ios9

Horizontally Center UILabel + UIImageView inside UIView with Autolayout


First Problem:

I have UIView that contains UILabel (dynamic text) + UIImage. I want them to be centered inside the UIView. Just like these images:

enter image description here

enter image description here

The answer here is out of date and now we have stack view maybe it can make the task easier.

Second Problem:

I have three UIView's next to each other each one has UIImageView + UILabel that should be centered in their container (Problem 1). In the iPhone 4s who has a small width screen the text breaks the layout, like in this image :

enter image description here

I use Xcode 7.0 | Target iOS8 and above | Swift 2


Solution

  • This is actually pretty easy to do in pure Autolayout/IB with no code. It ends up looking something like this: enter image description here

    Here's the storyboard file with the view so you can see the constraints easily. It uses the same subview wrapper technique, but the trick to getting the labels to shrink/cut off as needed is adding >= 0 constraints to both sides of the wrapper view, keeping it from expanding past the borders of the parent view, which in turn keeps the label from growing.

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