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.
I had the same issue, but was able to get the UILabel to wrap correctly by setting up the following constraints on the label
You also must have constraints leading from the top to the bottom of the scroll view. For instance, if you only have the label you must set Top Space and Bottom Space to Superview. If you don't, it will have an ambiguous scrollable content height.
To prevent horizontal scrolling of the scroll view, check "Direction Lock Enabled" and call setContentOffset properly inside the scrollViewDidScroll method (see the first answer for this question for the details).
Try using UILabel's
preferredMaxLayoutWidth
and set it to parent's view width.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With