Search code examples
iosswiftuitextviewswift5

How can I disable the return key in a UITextView based on the number of empty rows in the UITextView?


Both TikTok & Instagram (iOS) have a mechanism built into their edit profile biography code which enables the user to use the return key and create separation lines in user's profile biographies. However, after a certain number of lines returned with no text in the lines, they prevent the user from using the return key again.

How can one do this?

I understand how to prevent the return key from being used if the present line the cursor is on is empty, using the following:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        
  guard text.rangeOfCharacter(from: CharacterSet.newlines) == nil else {
    return false
  }
  return true

Moreover, I need help figuring out how to detect, for example, that 4 lines are empty, and stating that if 4 lines are empty, preventing the user from using the return key.


Solution

  • This may need fine tuning for edge cases but this would be my starting point for sure. The idea is to check the last 4 inputs into the text view with the current input and decide what to do with it. This particular code would prevent the user from creating a fourth consecutive empty line.

    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if text == "\n",
           textView.text.hasSuffix("\n\n\n\n") {
            return false
        }
        return true
    }