How to disable alertview's button in iPhone?
UPDATE 2: For Swift 5.1
<#your alert controller#>.addTextField {(tf) in
//... set your tf characteristics i.e .keyboardType here
NotificationCenter.default.addObserver(forName: UITextField.textDidChangeNotification,
object: tf,
queue: OperationQueue.main) { _ in
//enable or disable the selected action depending on whether the textField text is empty
<#your alert controller#>.actions[0].isEnabled = !tf.text!.isEmpty
}
}
posting this to update the response since ios 5 :
- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
UITextField *textField = [alertView textFieldAtIndex:0];
if ([textField.text length] == 0)
{
return NO;
}
return YES;
}
UPDATE:iOS 8 Since Apple have deprecated the UIAlertView in favour of the UIAlertController. There is no longer a delegate call to alertViewShouldEnableFirstOtherButton:
So instead you would set the buttons enabled property via the UITextFieldTextDidChangeNotification
Add a textView to the alert with
- (void)addTextFieldWithConfigurationHandler:(void (^)(UITextField *textField))configurationHandler
[<#your alert#> addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.delegate = self;
textField.tag = 0; //set a tag to 0 though better to use a #define
}];
Then implement the delegate method
- (void)textFieldDidBeginEditing:(UITextField *)textField
- (void)textFieldDidBeginEditing:(UITextField *)textField{
//in here we want to listen for the "UITextFieldTextDidChangeNotification"
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(textFieldHasText:)
name:UITextFieldTextDidChangeNotification
object:textField];
}
When the text in textField changes it will invoke a call to "textFieldHasText:" and pass along a NSNotification*
-(void)textFieldHasText:(NSNotification*)notification{
//inside the notification is the object property which is the textField
//we cast the object to a UITextField*
if([[(UITextField*)notification.object text] length] == 0){
//The UIAlertController has actions which are its buttons.
//You can get all the actions "buttons" from the `actions` array
//we have just one so its at index 0
[<#your alert#>.actions[0] setEnabled:NO];
}
else{
[<#your alert#>.actions[0] setEnabled:YES];
}
}
Don't forget to remove your observer when done
I wanted to extend the answer by Ryan Forsyth by adding this. If you add a Default styled UIAlertView, you can get an out of range exception if you try to access a textfield as none exist, so check your view style first.
-(BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView*)alertView
{
if(alertView.alertViewStyle == UIAlertViewStyleLoginAndPasswordInput ||
alertView.alertViewStyle == UIAlertViewStylePlainTextInput ||
alertView.alertViewStyle == UIAlertViewStyleSecureTextInput)
{
NSString* text = [[alertView textFieldAtIndex:0] text];
return ([text length] > 0);
}
else if (alertView.alertViewStyle == UIAlertViewStyleDefault)
return true;
else
return false;
}