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.)
If you have a UITextField or UITextView and want to stop users typing in more than a certain number of letters, you need to set yourself as the delegate for the control then implement either shouldChangeCharactersIn (for text fields) or shouldChangeTextIn (for text views).
Create textLimit method This is the first step in limiting the characters for a text field or a text view. We need to create a method that will limit the the number of characters based on the current character count and the additional/new text that will get appended to the current value of the text field or text view.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With