Gabe Spound
Gabe Spound

Reputation: 146

Multiple Line Label with word wrapping

This seems like it would be intuitive, but I've been trying to get text to stop going off screen for 45 minutes. Here is my viewDidLoad():

override func viewDidLoad() {
    super.viewDidLoad()
    orgTitle.numberOfLines = 0
    orgTitle.lineBreakMode = .byWordWrapping
    orgTitle.frame.size.width = self.view.frame.size.width - 20
    orgTitle.sizeToFit()

    orgDesc.numberOfLines = 0
    orgDesc.lineBreakMode = .byWordWrapping
    orgDesc.frame.size.width = self.view.frame.size.width - 20
    orgDesc.sizeToFit()

    self.orgTitle.text = self.oTitle
    self.orgDesc.text = self.desc
    self.orgImage.image = self.image
}

I attached a screenshot of the issue as well as the settings for my label. Label Settings Screenshot of issue

Upvotes: 0

Views: 936

Answers (1)

MathewS
MathewS

Reputation: 2307

I find it a lot easier to use constraints to set layout rather than manually adjusting the frame...

But if, for whatever reason, you want to manually set the frame of the label I'd suggest two things:

  1. Like like @rmaddy mentions, viewDidLoad is too early in the view controller lifecycle for the frame to be correct. Try overriding layoutSubviews and moving the frame adjustments into that method.

  2. For a UILabel with numberOfLines set to 0, you'll also want to set the labels preferredmaxlayoutwidth property to help it figure out how many lines it needs to be (not needed if using constraints).

Also, if you're willing to target iOS9 and above, UIStackView is really nice addition to UIKit to help with this sort of layout where subviews get pushed down from potential increasing height of multi-line labels.

Here's some screen grabs of adding a stack view to hold 2 UILabels, and then constraints that pin the stackview's left, top, and right edges to the superview:

enter image description here

With the layout defined in your storyboard, your viewDidLoad becomes a lot simpler with just setting the actual content for the labels:

override func viewDidLoad() {
    super.viewDidLoad()

    self.orgTitle.text = self.oTitle
    self.orgDesc.text = self.desc
    self.orgImage.image = self.image
}

Upvotes: 2

Related Questions