0

I need a textView to have a line limit where return (or new line) is disabled for the fifth line, in other words, max 4 lines inside textView. I've tried some things and this is the closest I've come but I can't get it to work:

   func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

    if text == "\n" { // Line added
        lineCount += 1

        if lineCount == 5 {
            print("No more! lineCount at \(lineCount)")
            lineCount -= 1
            textView.deleteBackward()
        }

    } else if !text.isEmpty { // Character added
        descCount += 1

    } else if range.length == 1 && textView.text.characters.last == "\n" { // Line deleted
        lineCount -= 1

    } else if text == "" && descCount != 0 { // Character deleted
        descCount -= 1
    }

    let newLength = descCount + text.characters.count - range.length - lineCount // text.characters.count counts /n characters

    return newLength <= 202 // Arbitrary number
}

Thanks in advance.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
rodrigochousal
  • 401
  • 4
  • 19
  • What exactly happens when you add a fifth line? It would be helpful to know if your message is printed (i.e. if the code in the statement is executed). – Benjamin Lowry Sep 23 '16 at 02:32
  • Possible duplicate of [How to limit the number of lines in UITextView?](http://stackoverflow.com/questions/32889495/how-to-limit-the-number-of-lines-in-uitextview) – Do2 Sep 23 '16 at 02:48
  • 1
    Possible duplicate of [Limit the number of lines for UITextview](http://stackoverflow.com/questions/5225763/limit-the-number-of-lines-for-uitextview) – Chen Wei Sep 23 '16 at 03:08

0 Answers0