0

I want to restrict my textview to 50 characters. I did it, but I am unable to press backspace after 50 characters. How to solve the problem ? My code is as below (Note: 'txtv' is my textview name)

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

        if (self.txtv.text.characters.count) >= 50 {
         return false
        }
        return true
    }

2 Answers2

1

if users cutting text, or deleting strings longer than a single character (ie if they select and then hit backspace), do like this

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
return textView.text.characters.count + (text.characters.count - range.length) <= 50
}
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
0

You haven't check incoming text, you should do that before before limiting text input.

if text.characters.count == 0 { // if backspace
    return true
}

if (self.txtv.text.characters.count) >= 50 {
     return false
    }
    return true
}
RJE
  • 781
  • 6
  • 14