Raoul
Raoul

Reputation: 153

UITextView: Automatically break line when reached a fixed width

I'm working on a view which holds a UITextView. Estimating the correct height for the content works just fine but when continuously typing the content grows horizontally over the border. Which looks like this:

enter image description here

Is there any handy solution which automatically breaks the line when reaching the, through auto layout, defined max width ?

Upvotes: 1

Views: 1359

Answers (2)

Raoul
Raoul

Reputation: 153

The solution I came up with is a pretty simple approach:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    let size = textView.sizeThatFits(textView.frame.size)
    if size.width >= self.maxTextViewWidth {
        let subString = textView.text.suffix(1)
        textView.text.removeLast(1)
        textView.text.append(contentsOf: "\n" +  subString)
    }

    return true
}

Upvotes: 1

Arrabidas92
Arrabidas92

Reputation: 1153

If you want to fix a limit of caracters or number of lines, you can by implementing a method from UITextView delegate called func textView(UITextView, shouldChangeTextIn: NSRange, replacementText: String)

Upvotes: 0

Related Questions