UILabel not wrapping reliably

1.9k views Asked by At

It seems impossible to get the UILabel to adhere to the constraints in the way that I want it to consistently. The leading and trailing space constraints seem in effect but the label is just truncating the lines instead of expanding to new lines.

please stop truncating

I do have the numberOfLines of the UILabel set to 0. I have also tried the suggestion listed here: UILabel not wrapping text correctly sometimes (auto layout) and it didn't seem to work reliably. The last thing I tried was setting the setContentCompressionResistancePriority property to Fitted and Low but it doesn't work for everything in the UITableView at the same time. In fact, depending on if the tableview gets refreshed, it looks like all the wrapping can get undone.

The only thing that I tried that seemed to work well was to set the preferredMaxLayoutWidth of the UILabel to a constant. I was just hoping to use it as a last resort to avoid calculating how wide the label should be at runtime. Surely, there's an out of the box way to get what I want.

2

There are 2 answers

2
mango On BEST ANSWER

The key to getting it to work correctly was to ask the view to reset the layout after the constraints had been applied and all the text had been set. I merely added these lines to my custom UITableViewCell after I had set the data that it needed:

    //set data
    //set constraints

    ...

    contentView.setNeedsLayout()
    contentView.layoutIfNeeded()
 }

I realized this was the solution because the view kept reporting their initial frame sizes instead of sizes after being affected by their constraints. For some reason, all the other views looked correct but not the UILabels.

I found the solution in the answer posted here: https://stackoverflow.com/a/13542580/1637033

5
Sohel L. On

You can calculate height of of the UILabel runtime as per the content

func heightForLabel(text:String, font:UIFont, width:CGFloat) -> CGFloat
    {
        let label:UILabel = UILabel(frame: CGRectMake(0, 0, width, CGFloat.max))
        label.numberOfLines = 0
        label.lineBreakMode = NSLineBreakMode.ByWordWrapping
        label.font = font
        label.text = text

        label.sizeToFit()
        return label.frame.height

    }