Search code examples
iosautolayoutios-autolayoutintrinsic-content-size

Multiline UILabel same width as intrinsic content sized UILabel


I'm trying to align two UILabel's using Auto Layout, where the first label has no set width but using intrinsic content size and the second should be the same width as the first, wrapping text to new lines.

Ideally the second label should have number lines set to 0 to work with Dynamic Type, but I've set it to 2 for the time being and even given it a specific height. Yet when I try to align either equal widths or trailing, the intrinsic content size label expands to the width of the multiline label as if it was all on one line (see below illustration).

What I'm after: The effect I'm after

What I'm seeing: The effect I'm getting

Is there any way for me to achieve what I want without specifying a width for the first label? I'd like it to expand with the content to account for dynamic type, and for the second label to have the same width and wrap all text to a new line.


Solution

  • You can do it without hooking anything to the code. The key point of this solution is the content hugging priority for the label which size will be calculated based entirely on the intrinsic content size.

    Intrinsic content size label

    • Set the horizontal content hugging priority to required (1000)

    Multiline label (lorem ipsum label)

    • Align leading to Intrinsic content size label
    • Align trailing to Intrinsic content size label


    Xcode configurations for both labels (left: Intrinsic, right: Multilabel)

    configuration of intrinsic content size label configuration of multiline label