Search code examples
iosobjective-cswiftxcodeios9

AlertViewController should not be dismissed when I enter empty AlertView textfield in iOS


I have added a textfield in AlertViewController. I don't type anything in the textfield and enter the OK button meaning dismiss the alert view. How should I check the alert textfield length is zero so that alert button actions are disabled. Please help me...


Solution

  • Try this code.

    //
    //  ViewController.m
    //  AlertControllerDemo
    //
    //  Created by Nilesh on 8/10/16.
    //  Copyright © 2016 Nilesh. All rights reserved.
    //
    
    #import "ViewController.h"
    
    @interface ViewController ()<UITextFieldDelegate>
    @property(nonatomic, strong)UIAlertAction *okAction;
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    - (IBAction)showAlertButtonAction:(id)sender {
    
        self.okAction = [UIAlertAction actionWithTitle:@"Okay"
                                                 style:UIAlertActionStyleDefault
                                               handler:nil];
        self.okAction.enabled = NO;
    
        UIAlertController *controller = [UIAlertController alertControllerWithTitle:nil
                                                                            message:@"Please Enter your text"
                                                                     preferredStyle:UIAlertControllerStyleAlert];
    
        [controller addTextFieldWithConfigurationHandler:^(UITextField *textField) {
    
            textField.delegate = self;
        }];
    
        [controller addAction:self.okAction];
        [self presentViewController:controller animated:YES completion:nil];
    }
    
    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
        NSString *finalString = [textField.text stringByReplacingCharactersInRange:range withString:string];
        [self.okAction setEnabled:(finalString.length >= 1)];
        return YES;
    }
    @end
    

    Before Entering Text After Entering Text