'Disable button in UIAlertView while text field is empty

I make an AlertViewController with textField that asks user to type a name of new item for data model.

So I want to keep submit button disabled while text field is empty. In other case, when I create @IBOutlet in ViewController for textfield from storyboard I could just use some methods from UITextFieldDelegate protocol and solve problem without your help.

But now I can't.



Solution 1:[1]

New Swift 4.2 Update

NotificationCenter.default.addObserver(
  forName: UITextField.textDidChangeNotification,
  object: alert.textFields?.first,
  queue: .main) { (notification) -> Void in
    guard let textFieldText = alert.textFields?.first?.text else { return }
    saveAction.enabled = self.isValidEmail(textFieldText) && !textFieldText.isEmpty
}

Solution 2:[2]

add this code in viewDidLoad method

let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(
 self,
 selector: "textFieldTextChanged:",
 name:UITextFieldTextDidChangeNotification,
 object: nil
)

and this method in ViewController

func textFieldTextChanged(sender : AnyObject) {
//your code
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 thisIsTheFoxe
Solution 2 shalu tyagi