Line break after 20 characters in a label

Viewed 26

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.

1 Answers

You can use a String extension:

extension String {

    mutating func insert(sourceString: String, string: String, indx: Int) {

        do {

            if indx > sourceString.count {
              
            } else {

                try insert(contentsOf: string, at: index(startIndex, offsetBy: indx))
            }

        // This do-catch is to make sure nothing happens if is an issue

        } catch Your.Execption {
          
        }
    }
}

And then use it like this:

myString.insert(sourceString: myString, string: "\n", indx: 20)

Related