Two ·func textField· at the same time (Swift 4.x-5.x)

Two ·func textField· at the same time (Swift 4.x)
Two ·func textField· at the same time (Swift 4.x)

It just so happens that in the Swift we cannot use func textField more than once, even if you have few solutions for your application.

What to do in this situation? You just need to put all your code snippets into one func textField. That’s all.

For example, I posted articles about how to disable UIButton if UITextField is empty and how to set the maximum numbers of characters of the UITextField. Your app will not work that way:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let text = (yourTextField.text! as NSString).replacingCharacters(in: range, with: string)
   if !text.isEmpty{
        yourButton?.isUserInteractionEnabled = true
        yourButton?.alpha = 1.0
   } else {
        yourButton?.isUserInteractionEnabled = false
        yourButton?.alpha = 0.5
      }
     return true
}

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
  let maxLength = 3
  let currentString: NSString = textField.text! as NSString
  let newString: NSString =
    currentString.replacingCharacters(in: range, with: string) as NSString
  return newString.length <= maxLength
}

Your app will work in this way:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let text = (yourTextField.text! as NSString).replacingCharacters(in: range, with: string)
   if !text.isEmpty{
        yourButton?.isUserInteractionEnabled = true
        yourButton?.alpha = 1.0
   } else {
        yourButton?.isUserInteractionEnabled = false
        yourButton?.alpha = 0.5
      }
  let maxLength = 3
  let currentString: NSString = textField.text! as NSString
  let newString: NSString =
    currentString.replacingCharacters(in: range, with: string) as NSString
  return newString.length <= maxLength
}