Search code examples
iosuilabel

Change LineBreak Characters from UILabel


When i Add let say following text into my UILabel,

Lorem, Ipsum, is simply, dummy text of, the printing, and typesetting industry.

Now, let say my UILabel's width is limited but number of lines = 0(unlimited), then it will show the text like:

Lorem, Ipsum, is
simply, dummy text
of, the printing,
and typesetting 
industry.

Here, you can see that line breaks are done at whitespaces, now i want them to update, and i want line breaks only when there is newline or comma(,) is there. So, How can i Implement that.

My Expected output is

Lorem, Ipsum,
is simply,
dummy text of,
the printing,
and typesetti
ng industry.

Solution

  • Tested solution

    Create text and customText empty string

    let text = "Lorem, Ipsum, is simply, dummy text of, the printing, and typesetting industry."
    var customText = ""
    

    Populate customText by substituting spaces with non-breakable spaces \u{00a0} if previous character is not ,

    text.characters.enumerated().forEach { (idx, character) in
        let prevChar = text[text.index(text.startIndex, offsetBy: max(0, idx-1))]
        if character == " " && prevChar != "," {
            customText.append("\u{00a0}")
        }
        else {
            customText.append(character)
        }
    }
    

    Create your label and assign customText to its text

    let label = UILabel(frame: CGRect(x: 0, y: 0, width: 115, height: 5))
    label.numberOfLines = 0
    label.text = customText
    label.sizeToFit()