Richard Witherspoon
Richard Witherspoon

Reputation: 5019

UILabel Minimum Number Of Lines

If you take a close look an an iMessage conversation cell, you’ll notice that the preview text is always two lines long. This can’t be a hard coded row height because the rows adjust to dynamic type. How can you always force a label to take up a certain number of lines even if there isn’t enough text to do so?

enter image description here

Upvotes: 3

Views: 1583

Answers (2)

NNikN
NNikN

Reputation: 3850

One way I think this could be possible is having a UIView as a parent of the UILabel.

  1. Fix the height of the UIView based on device size class. Let's say for example 50 points for Width = Compact and Height = Regular.
  2. Embed UILabel in UIView
  3. Set number of Lines = 0 for UILabel
  4. Now match UILabel leading , trailing ,top edge with the superview and leave the height as it is , also don't set the bottom constraints.
  5. Select the superview i.e the UIView and UILabel together and select Equal Heights.

Open the constraint window and change label height less than or equal to SuperView height.

Short Message

enter image description here

Long Message

enter image description here

Height Constraint of the UILabel with respect to SuperView.

enter image description here

Upvotes: 0

matt
matt

Reputation: 534893

Set the label's numberOfLines to 2 and end the label's text with a linefeed \n. Set the wrapping to word wrap to prevent the ellipses from appearing.

This guarantees that the label text consists of at least 2 lines worth of material. Thus it can never be less than 2 lines, and since the maximum number of lines is 2, it can never be more than 2 lines. Thus it will always be (wait for it) 2 lines.

enter image description here

Upvotes: 4

Related Questions