I have a label. If the text count in that label is 30, then after the 20th character there should be a line break. How can we achieve that?
I have the label setup as below.
let label = MyLabelText()
label.numberOfLines = 2
label.lineBreakMode = .byTruncatingTail
label.setContentHuggingPriority(.defaultHigh, for: .horizontal)
Both line break and number of lines are defined. But I’m not sure how to go to the second line after the 20th character.
2
Answers
You can use a
String
extension:And then use it like this:
myString.insert(sourceString: myString, string: "n", indx: 20)
A clean way to achieve this is to extend
String
so it can provide a ‘wrapped’ version of itself, and then use this in a subclass ofUILabel
to keep things clean at the point of use.So extend
String
to wrap itself into a multi-line string at a certain character width:A couple of things of note:
width + 1
characters. Helpfully sequence enumerations are 0-indexed so you get the+1
for free 🙂reduce
closure into a single line ternary operation. I did initially and it was hideous to read, so anif...else
is far more maintainable.Once this is in place, creating the custom
UILAbel
is pretty straightforward. Create a subclass and override thetext
property:Implementation is then as simple as