Setting maximum number of characters of `UITextView ` and `UITextField `

biggreentree picture biggreentree · Oct 4, 2015 · Viewed 40.7k times · Source

I'd like to set a maximum number of characters allowed to be typed both in a UITextView and a UITextField. This number will be then shown in a little label (for user's reference, Twitter Style.)

Answer

Abhinav picture Abhinav · Oct 4, 2015

Update Swift 4.X

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    let newText = (textView.text as NSString).replacingCharacters(in: range, with: text)
    let numberOfChars = newText.count
    return numberOfChars < 10    // 10 Limit Value
}

Try this out:

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
    let newText = (textView.text as NSString).stringByReplacingCharactersInRange(range, withString: text)
    let numberOfChars = newText.characters.count // for Swift use count(newText)
    return numberOfChars < 10;
}