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

47,620

Solution 1

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;
}

Solution 2

SWIFT 4

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

Solution 3

Swift 4:

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

Solution 4

Try this out:-

 func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
    print("chars \(textView.text.characters.count) \( text)")

    if(textView.text.characters.count > 20 && range.length == 0) {
        print("Please summarize in 20 characters or less")
        return false;
    }

    return true;
}

Solution 5

Swift 3.0

Just override this UITextFieldDelegate function, set the desired characterLimit variable and you are good to go:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool 
{        
        let characterLimit = 5
        let newText = NSString(string: textField.text!).replacingCharacters(in: range, with: string)
        let numberOfChars = newText.characters.count
        return numberOfChars < characterLimit
}
Share:
47,620
biggreentree
Author by

biggreentree

Apple and Swift Enthusiast, learning coding never ends!

Updated on July 09, 2022

Comments

  • biggreentree
    biggreentree almost 2 years

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

  • rmaddy
    rmaddy over 8 years
    This is correct but why is the variable named numberOfLines when it is the number of characters?
  • William Kinaan
    William Kinaan over 8 years
    yes this is correct, i forgot about the number of lines
  • rmaddy
    rmaddy over 8 years
    @WilliamKinaan What number of lines? There's nothing in the question about limiting the number of lines.
  • Abhinav
    Abhinav over 8 years
    Thanks @rmaddy for pointing out. It was a typo in a rush :-), corrected it now!
  • biggreentree
    biggreentree over 8 years
    I added this code in ViewDidLoad and replaced textView: UITextView with myMessageTextView is it right? Now I got this error String does not have a member named 'characters'. I'm using swift 1.2 at now, could be a problem?
  • Abhinav
    Abhinav over 8 years
    Yes, as I mentioned in my code. For Swift use count(newText). I am using Swift 2.
  • Abhinav
    Abhinav over 8 years
    Hey ... 1 minute, you said you added my code in viewDidLoad? Well thats not correct. In your viewDidLoad you would add your view controller as delegate to your UITextField something like this myMessageObjectLabel.delegate = self. The code that I have shared above is a delegate call back from UITextField - add in your class file as an independent function and it should get called back for each character typed in by user in your text field.
  • Abhinav
    Abhinav over 8 years
    You need to conform to UITextViewDelegate protocol. I guess by mistake you added text filed delegate. Please check that out. @biggreentree
  • Abhinav
    Abhinav over 8 years
    I am sure its very simple stuff. Would it be possible for you to share the project on github? I can take a look. @biggreentree
  • Abhinav
    Abhinav over 8 years
    Hey, your method signature is totally off. Take a look at my post. You should not use self.startingMessageTextView , instead it should be UITextView. Use my method word by word. @biggreentree
  • biggreentree
    biggreentree over 8 years
    you are totally right, I changed it because in my mind I was acting only on that selected UITextView everything works great! thanks I'll do the same on my UITextField for object
  • Abhinav
    Abhinav over 8 years
  • Roberto
    Roberto over 7 years
    Shouldn't the last line be return numberOfChars <= 10; (the less-than symbol should be less-than-or-equal-to)?
  • Steve
    Steve over 6 years
    @Abhinav how to restrict the copied text in here? like, clipboard got 2000 characters string where textview allows 1500 character, so when i paste the long string it let the textview empty instead of copying 1500 characters.
  • Lance Samaria
    Lance Samaria almost 6 years
    in Swift 4 its: let numberOfChars = newText.count
  • Yaroslav Dukal
    Yaroslav Dukal almost 6 years
    @LanceSamaria thanks, updated my answer to Swift 4, since Swift 3 is no longer relative..
  • Yaroslav Dukal
    Yaroslav Dukal over 4 years
    what's adjust frames for ?
  • Swany
    Swany about 4 years
    If you want to allow the user to delete chars when they "are over the limit" (can happen if you lower the char limit and user is editing with old (longer text), add a guard...guard !text.isEmpty else { return true }