How to do a live UITextField count while typing (Swift)?

后端 未结 10 1233
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 13:37

I would like to count the character when user keep typing in UITextField with swift.

Image of Field and Label:

10条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 14:35

    In Swift
    viewDidLoad {
    self.yourTextView.delegate = self
    self.updateCharacterCount()
    }
    
    func updateCharacterCount() {
        self.yourLabel.text = "\((65) - self.yourTextView.text.characters.count)"  
    }
    
    func textViewDidChange(textView: UITextView) {
        self.updateCharacterCount()
    }
    
    
    func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
        self.updateCharacterCount()
        return textView.text.characters.count +  (text.characters.count - range.length) <= 65
    }
    

提交回复
热议问题