Adam Johns Adam Johns - 1 year ago 73
iOS Question

UILabel won't word wrap inside UIScrollView with AutoLayout

I have a

UILabel
inside a
UIScrollView
that I am trying to word wrap. I want to use AutoLayout for the layout configuration. The
UILabel
word wraps perfectly when it is not inside a
UIScrollView
. I just have to set the number of lines to 0 and set the line break mode to word wrap.

However, when I put the
UILabel
inside a
UIScrollView
, the word wrapping ceases to work. I have already checked "Dynamic UILabel height inside UIScrollView with AutoLayout" and "Correctly Size UILabel inside UIScrollView using Interface Builder and Autolayout?", but neither of those questions have answers that help me.

I have set up a test project illustrating exactly what I am talking about if someone wants to have a look at it.

Answer Source

The reason is that constraints inside a scroll view, pinned to the scroll view, do not mean what you think they mean. They have to do with determining the contentSize of the scroll view from the inside out; they do not of themselves determine the size of the things inside the scrollview from the outside in. See my answer here: https://stackoverflow.com/a/13548039/341994

The simplest solution in your case is to use an intermediate content view, so that you have this hierarchy:

scroll view
    content view
        label

Now give the content view absolute width and height constraints and pin it on all four sides to the scroll view. Now the label will work as you expect. The content view has sufficient constraints both to set its own size absolutely and to constrain the scroll view's contentSize from the inside. The constraints on the label, meanwhile, are not to the scroll view but to the content view, and since the content view has a fixed size and is a normal view (not a scroll view), the constraints on the label do what you expect.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download