Enable UIAlertAction of UIAlertController only after input

前端 未结 6 1706
感情败类
感情败类 2020-12-16 01:39

I am using a UIAlertController to present a dialog with a UITextField and one UIAlertAction button labeled \"Ok\". How do I disable th

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-16 02:01

    Add following property in your header file

    @property(nonatomic, strong)UIAlertAction *okAction;   
    

    then copy the following code in your viewDidLoad method of your ViewController

    self.okAction = [UIAlertAction actionWithTitle:@"OK"
                                             style:UIAlertActionStyleDefault
                                           handler:nil];
    self.okAction.enabled = NO;
    
    UIAlertController *controller = [UIAlertController alertControllerWithTitle:nil
                                                                        message:@"Enter your text"
                                                                 preferredStyle:UIAlertControllerStyleAlert];
    
    [controller addTextFieldWithConfigurationHandler:^(UITextField *textField) {
    
        textField.delegate = self;
    }];
    
    [controller addAction:self.okAction];
    [self presentViewController:controller animated:YES completion:nil];
    

    Also implement the following UITextField delegate method in your Class

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
        NSString *finalString = [textField.text stringByReplacingCharactersInRange:range withString:string];
       [self.okAction setEnabled:(finalString.length >= 5)];
       return YES;
    }
    

    This should work

提交回复
热议问题