Mehul Thakkar
Mehul Thakkar

Reputation: 12594

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.

Upvotes: 1

Views: 1181

Answers (4)

Jože Ws
Jože Ws

Reputation: 1814

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()

Upvotes: 2

BugFinder
BugFinder

Reputation: 147

Swift 3.0

Simply add text like this. I have tested this and here you go with your expected output, but don't forget to set the label height according to this.

label33.text = "Lorem Ipsum,\nis simply,\ndummy text of,\nthe printing,\nand typesetti\nng industry."

Upvotes: 0

LevinYan
LevinYan

Reputation: 56

Maybe you should subclass the UILabel,CustomLabel.You should calculate the content and commas and add \n。

Upvotes: 0

Ajjjjjjjj
Ajjjjjjjj

Reputation: 675

NSString *string = @"Lorem, Ipsum,\n is simply,\n dummy text of,\n the printing,\n and typesett\ning industry.";

Now use this string

Upvotes: 0

Related Questions