UILabel repeated text when limit number of lines with truncating and break line - iOS 15.4

Hi, I noticed a bug on UILabel only on iOS 15.4. If we have a UILabel with numberOfLines = 3 using byTruncatingHead and the text contains a \n, the last line replicates some characters from the previous line. Please take a look at the attached screenshot.

The code is very simple:

        var text = "A Person Name\nalso commented on Other Person\'s post: Hi Eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
        label.text = text
        label.numberOfLines = 3
        label.lineBreakMode = .byTruncatingHead

Note: UILabel has 32 horizontal margin constraints and I tested it on iPhone 12. I tested it on iPhone 11 running iOS 15.3 and it works fine.

I recently ran into this same issue in both UILabel and SwiftUI Text. It is possible to work around the bug by inserting zero-width spaces before the line break - at least as many as the number of characters that would fit on the first line if there was no \n in the string. Using the length of the text after the line break should guarantee correct rendering.

let zeroWidthNoBreakSpace =  "\u{feff}"
let firstLine = "A Person Name"
let secondLine = "also commented on Other Person\'s post: Hi Eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
let workaround = String().padding(toLength: firstLine.count, withPad: zeroWidthNoBreakSpace, startingAt: 0)
let text = firstLine + workaround + "\n" + secondLine

So this is definitely a bug introduced after iOS 15.2 (I'm guessing 15.5). UILabel with fixed number of lines, dynamic height, attributed text, and lineBreakMode .byTruncatingTail. Thanks to @JARinteractive's answer, I came up with a more generic solution:

private func padContentNewlinesWithSpaces(content: String, label: UILabel) -> String {
    let zeroWidthNoBreakSpace = "\u{feff}"
    let lines = content.components(separatedBy: "\n\n")
    var fixedContent = ""
    for l in 0..<min(lines.count, label.numberOfLines) {
      let line = lines[l]
      let spaces = String().padding(toLength: 100, withPad: zeroWidthNoBreakSpace, startingAt: 0) // 100 or some arbitrarily large number
      fixedContent += line + spaces + "\n\n"
    }
    return fixedContent
}
UILabel repeated text when limit number of lines with truncating and break line - iOS 15.4
 
 
Q