Search code examples
iosobjective-cuiscrollviewautolayout

Limit the height of a UILabel inside a UIScrollView


I have a UILabel inside a UIScrollView and the contentSize of the UIScrollView is determined by the amount of text in the UILabel. I have managed to define a minimum height for the contentView inside the UIScrollView by making the height, width and aspect ratio constraints optional.

This is how the hierarchy of the UIScrollView looks like -

UIScrollView
    contentView
        UILabel

In some cases, even when the text is huge and makes the label expand beyond it's frame, I wish to have the frame of the UILabel stick to it's square frame with the extra text getting truncated. I am using autolayout so I believe this won't be possible by merely setting the frame of the UILabel and it has something to do with changing the priorities of the constraints.

Constraints for the UILabel - The UILabel has its leading, trailing, top and bottom connected to the contentView.

Constraints for the UISCrollView-

Required

Trailing, Leading, Top and Bottom to the superview i.e. the UIScrollView

Optional

Equal height and width to the superview (UIScrollView) and aspect ratio = 1:1

EDIT

And I need to do it in a way that when I set the lineBreakMode of the UILabel to NSLineBreakByTruncatingTail, the text automatically gets truncated and textLabel.text only returns the visible text.


Solution

  • Ok, so if I understand everything correctly, you want to have an expandable label that either shows its entire text, or has a square form. This should as easy as enabling/disabling a constraint such that label.height <= label.width (or ==, depending on what you want it to look like if there is less text then would fit a square label). You can create this constraint in interface builder, add an outlet for it and then simply do:
    self.labelSquareConstraint.active = YES/NO;

    As to the question in your edit : there is no easy way to get the visible part of the text from a label, but there are some threads on SO about this, for example :
    Get truncated text from UILabel
    UILabel visible part of text
    Calculate the range of visible text in UILabel