0

I have a button in one class and textField in another. My goal is to achieve this: when textField is empty, the button is hidden, and then I add numbers to textField (it has 4 numbers), the button becomes visible.

I add target to my button:

let confirmButton: UIButton = {
let button = UIButton()

button.setTitle("Confirm", for: .normal)
button.layer.borderWidth = 1
button.layer.borderColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)

button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: #selector(confirmation.textFieldDidEndEditing(_:)), for: .editingDidBegin)
return button

}()

And make this function in another class:

@objc func textFieldDidEndEditing(_ textField: UITextField) {
  if textField.text != "" {
  button.confirmButton.isHidden = false
  } else {
    button.confirmButton.isHidden = true
  }

But nothing changed. Help me, please, that l have to do to achieve my goal?

maytime
  • 111
  • 1
  • 12

1 Answers1

0

Use textField's delegate method

class MyViewController: UIViewController, UITextFieldDelegate {
    lazy var confirmButton: UIButton = {
        let button = UIButton()
        button.setTitle("Confirm", for: .normal)
        button.layer.borderWidth = 1
        button.layer.borderColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        button.isHidden = true // You probably want it to hidden first
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()

    lazy var textField = UITextField()

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self // Don't forget to set delegate
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        confirmButton.isHidden = newString.isEmpty
        return true // OR return newString.count <= 4 if you want to limit to maximum 4 characters/digits
    }
}
boa_in_samoa
  • 587
  • 7
  • 16
  • Thank you for your answer! But l can't understand where exactly in my ViewController l have to set 'textField.delegate = self'? – maytime Dec 17 '20 at 07:07
  • @MayaK You can set it in `viewDidLoad` or wherever you're setting up your text field. This will trigger an error saying that you cannot assign to type 'UITextFieldDelegate'. To fix it you'll have to add the protocol conformance like this: `MyViewController: UIViewController, UITextFieldDelegate {' – boa_in_samoa Dec 17 '20 at 11:48