Search code examples
iosuilabelswift4nsattributedstring

UILabel Attributed Text doesn't fill entire line before starting a new line


As you can see from the image, the background of the UILabel is set to yellow. The attributed text does not use all the space before wrapping to the next line ("at" should be in the first line). Any way to fix it?

enter image description here

The label is constructed as follows. It is inside a UICollectionView header, and positioned by autolayout

let astring = NSMutableAttributedString(string: "You asked friends, and people at ")
astring.append(NSAttributedString(string:"Pittsburgh", 
    attributes: [.font: UIFont.boldSystemFont(ofSize: 15)]))

let label = UILabel()
label.attributedText = astring

Solution

  • Yes, odd bug...

    One work-around, although I haven't done any testing on it except to see that it works in your case.

    Append a "no-width space" character at the end:

        let astring = NSMutableAttributedString(string: "You asked friends, and people at ")
        astring.append(NSAttributedString(string:"Pittsburgh",
                                          attributes: [.font: UIFont.boldSystemFont(ofSize: 15)]))
        astring.append(NSAttributedString(string:"\u{200b}",
                                          attributes: [.font: UIFont.systemFont(ofSize: 15)]))
    

    Result:

    enter image description here