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

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

    Here's how you could do it in Swift 3/4.

    First, make sure you've got your textField's delegate set in viewDidLoad.

    yourTextField.delegate = self
    

    Then, implement shouldChangeCharactersIn:

    extension YourViewController: UITextFieldDelegate {
        func textField(_ textFieldToChange: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
          // limit to 4 characters
          let characterCountLimit = 4
    
          // We need to figure out how many characters would be in the string after the change happens
          let startingLength = textFieldToChange.text?.characters.count ?? 0
          let lengthToAdd = string.characters.count
          let lengthToReplace = range.length
    
          let newLength = startingLength + lengthToAdd - lengthToReplace
    
          return newLength <= characterCountLimit
        } 
    }
    

    Additional details here

提交回复
热议问题