I am showing an alert on button click, which has a text field and OK/cancel buttons. I like ‘OK’ button to be displayed only if the user types in the text box.
Here is my code: I setup a function on text change. But it is not working as I intend to. Can anyone see what I am doing wrong.
appreciate your help.
(IBAction)displayAlertview:(id)sender{
UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"My Alert"
message:@"This is an alert."
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel
handler:^(UIAlertAction * action) {}];
[alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
[textField addTarget:self action:@selector(alertControllerTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}];
okAction.enabled = false;
[alert addAction:okAction];
[alert addAction:cancelAction];
[self presentViewController:alert animated:YES completion:nil];
}
-(void)alertControllerTextFieldDidChange:(UITextField *)sender{
UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
if (alertController) {
UITextField *someTextField = alertController.textFields.firstObject;
UIAlertAction *okAction = alertController.actions.lastObject;
okAction.enabled = true; //someTextField.text.length >2;
}
}