Search code examples
iosswiftuitextviewuitextviewdelegate

UITextView characters remaining


How can I set characters remaining on a UILabel for the UITextView?

I have done this for the UITextField, but the same code does not work..

This is what I have tried:

func textView(textView: UITextView, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
 {
        if string == ""
        {
            if plainTextView.text!.characters.count == 0
            {
                charCount = 0
                countLabel.text = String(format: "%i Characters Left", maxLength - charCount)
                return false
            }
            charCount = (plainTextView.text!.characters.count - 1)
            countLabel.text = String(format: "%i Characters Left", maxLength - charCount)
            return true
        }
        else
        {
            charCount = (plainTextView.text!.characters.count + 1)
            countLabel.text = String(format: "%i Characters Left", maxLength - charCount)

            if charCount >= maxLength + 1
            {
                charCount = maxLength
                countLabel.text = String(format: "%i Characters Left", maxLength - charCount)
                return false;
            }
        }
        return true
    }

Any suggestions?


Solution

  • try this

    import UIKit
    
    class ViewController: UITextViewDelegate {
        let maxLenghth = 200
        
        func textViewDidChange(_ textView: UITextView) {
            countLabel.text = "\(maxLength - textView.text.count)"
        }
        
        func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
            return textView.text.count + (text.count - range.length) <= maxLength
        }
    }