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

后端 未结 10 1200
佛祖请我去吃肉
佛祖请我去吃肉 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:40

    A very elegant and neat solution exists using UITextFieldDelegate. My solution uses the concept of selectors. In a selector you tell your compiler what function/action to perform when a particular event happens. In this case - typing in textfield. Make sure that you have set the textField delegate in storyboard.

    override func viewDidLoad() {
       super.viewDidLoad()
       yourTextField.addTarget(self, action: #selector(YourViewController.textFieldDidChange(_:)), for: UIControlEvents.EditingChanged)
    }
    
    @objc func textFieldDidChange(textField : UITextField){
       label.text = yourTextField.text?.count
    }
    

提交回复
热议问题