When trying to get dynamically created UILabel to wrap, text disappears

561 views Asked by At

I'm trying to display some description text that varies from a couple of words to a hundred words. I've set my UILabel to wrap to compensate using the code below

    descText.frame = CGRect(x: 115, y: 160, width: 465, height: 21)     
    descText.textAlignment = NSTextAlignment.Left
    descText.numberOfLines = 0
    descText.lineBreakMode = NSLineBreakMode.ByWordWrapping
    descText.sizeToFit()
    descText.Text = text
    dtlView.addSubview(descText)

If I remove descText.sizeToFit() the text reappears but won't wrap, the same happens if I try to set height in CGRect to CGFloat.max.

What am I missing?

2

There are 2 answers

0
user616076 On BEST ANSWER

Changing the position of sizeToFit() after assigning text did the job as suggested by Bartlomiej above

1
Shamsudheen TK On

Make use of ByCharWrapping instead of using ByWordWrapping

Also make sure to call sizeToFit() only after assigning the text.

descText.lineBreakMode = NSLineBreakMode.ByCharWrapping
descText.Text = text
descText.sizeToFit()