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

后端 未结 10 1236
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  猫巷女王i
    2020-12-05 14:15

    For multiple UITextView

    class ViewController: UIViewController, UITextViewDelegate {
    
     @IBOutlet weak var ticketSummaryTV: UITextView!
     @IBOutlet weak var ticketDescriptionTV: UITextView!
    
     @IBOutlet weak var summaryCountLbl: UILabel!
     @IBOutlet weak var descriptionCountLbl: UILabel!
    
     override func viewDidLoad() {
        super.viewDidLoad()
    
        // Do any additional setup after loading the view.
    
        ticketSummaryTV.delegate = self
        ticketDescriptionTV.delegate = self
    
        self.updateCharacterCount()
     }
    
     func updateCharacterCount() {
        let summaryCount = self.ticketSummaryTV.text.characters.count
        let descriptionCount = self.ticketDescriptionTV.text.characters.count
    
        self.summaryCountLbl.text = "\((0) + summaryCount)/50"
    
        self.descriptionCountLbl.text = "\((0) + descriptionCount)/500"
     }
    
     func textViewDidChange(_ textView: UITextView) {
        self.updateCharacterCount()
     }
    
    
     func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool{
        if(textView == ticketSummaryTV){
           return textView.text.characters.count +  (text.characters.count - range.length) <= 50
        }else if(textView == ticketDescriptionTV){
            return textView.text.characters.count +  (text.characters.count - range.length) <= 500
        }
        return false
     }
    }
    

提交回复
热议问题