Swift 5.3
Add UITextFieldDelegate in you viewController with outlets
class ViewController: UIViewController, UITextFieldDelegate{
@IBOutlet weak var txtGroupName: UITextField!
@IBOutlet weak var lblWordCount: UILabel!
Add textfeild delegate in your viewDidLoad() like below
override func viewDidLoad() {
super.viewDidLoad()
txtGroupName.addTarget(self, action: #selector(self.textFieldDidChange(textField:)), for: UIControl.Event.editingChanged)
}
@objc func textFieldDidChange(textField : UITextField){
self.lblWordCount.text = "\(self.txtGroupName.text!.count)/"+"\(65)"
}
We have set also meximum text limit 65 . you can replace 65 to what you want.
extension viewController:UITextFieldDelegate{
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if !(textField.text?.isEmpty ?? true){
return textField.text!.count + (string.count - range.length) <= 65
}
return true
}
}
It's output is like below
