Gokulraj Rajan
Gokulraj Rajan

Reputation: 57

allowing backspace in textview in swift 2

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
    }

Upvotes: 0

Views: 526

Answers (2)

RJE
RJE

Reputation: 891

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
}

Upvotes: 0

Anbu.Karthik
Anbu.Karthik

Reputation: 82759

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
}

Upvotes: 1

Related Questions