How to make UIButton hidden or not depends of UITextField

123 Views Asked by At

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?

1

There are 1 best solutions below

2
On

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
    }
}