Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering a variable width column of text in a UIScrollView using Auto Layout

I have a seemingly simple design that I can't express using Auto Layout constraints: in a UIScrollView, I need to show a centered column of text that has a minimum width of 300 pts and a maximum width of 500 pts (maintaining a margin of at least 10 pts in all cases.)

The column of text is actually a UIStackView, but that doesn't really matter for this discussion, the view could just as easily be a UIImageView with aspect fit.

I've tried using padding views with different content hugging and compression resistance, a stack view with a horizontal axis, width constraints with less-than-or-equal constants, etc. I want to do it all within the storyboard, sniffing around during layout changes or using size classes feels like cheating.

(Some of my experiments have caused Xcode to hang while updating the storyboard: giving me a painful hint that there's no solution for these kinds of constraints.)

And before you suggest it, I have read about the subtleties of UIScrollView and Auto Layout.

This seems like an unsolvable problem, which is a shame. It's a very common pattern and something designers love to use with CSS (using min-width and max-width). I hope that I'm missing something here and that someone with a deeper knowledge of auto layout can explain a way to do this (and act as a reference for others who would like to do the same thing.)

Update: The suggestions by Adam and Ben below are very helpful for achieving this layout. But as soon as you get multiple blocks of text the auto layout iterative solver can't handle it (and Xcode hangs.) For more information: http://openradar.appspot.com/25173433

like image 970
chockenberry Avatar asked Oct 19 '22 13:10

chockenberry


1 Answers

This one is actually pretty straightforward! I've included a storyboard file as a demo. The key bits for the text inside of the content view:

  • Leading/Trailing Margins >= 10
  • Width >= 300
  • Width <= 500
  • Center Align

No priority changes are required, unless you have other content that is going to take precedence.

enter image description here

like image 88
Ben Avatar answered Oct 21 '22 09:10

Ben