0

I am using a text View for content input for users, but I cannot limit the amount of times user hits enter to create new lines, how can I limit the textView to 2 new lines max?

Example:

current

"Start





end"

Desired:

"limit


2 


empty lines"
Noah Iarrobino
  • 1,435
  • 1
  • 10
  • 31

1 Answers1

3

You can make your view controller the delegate of your text view and use replacingOccurrences to replace 4 or more new lines with 3 new lines, you would need to avoid new lines also at the beginning of your string:

class ViewController: UIViewController, UITextViewDelegate {

    @IBOutlet weak var textView: UITextView!
    override func viewDidLoad() {
        super.viewDidLoad()
        textView.delegate = self
    }
    func textViewDidChange(_ textView: UITextView) {
        // avoid new lines also at the beginning
        textView.text = textView.text.replacingOccurrences(of: "^\n", with: "", options: .regularExpression)
        // avoids 4 or more new lines after some text
        textView.text = textView.text.replacingOccurrences(of: "\n{4,}", with: "\n\n\n", options: .regularExpression)
    }
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571