Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.)

like image 297
biggreentree Avatar asked Oct 04 '15 16:10

biggreentree


People also ask

How do I limit the number of characters in UITextField or UITextView?

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).

How do I limit the number of characters in a text field in Swift?

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.


1 Answers

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; } 
like image 119
Abhinav Avatar answered Sep 23 '22 08:09

Abhinav