Wednesday, 10 August 2016

Create Alert Controller with textfield in iOS

Today we will see how to give textfield in AlertController. And we will put condition that if users do not fills anything in the textfield, we will not dismiss it.

Steps:
1.  Create a new Xcode Project.
2. Now go to storyboard and take a button and make proper IBOutlet connection for it.
3. Now write this code in Your ViewController.m

#import "ViewController.h"

@interface ViewController ()<UITextFieldDelegate>
@property(nonatomic, strong)UIAlertAction *okayAction;

@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.okayAction = [UIAlertAction actionWithTitle:@"Okay"
                                             style:UIAlertActionStyleDefault
                                           handler:nil];
    self.okayAction.enabled = NO;
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil
                                                                        message:@"Please Enter your text"
                                                                 preferredStyle:UIAlertControllerStyleAlert];
    
    [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        
        textField.delegate = self;
    }];
    
    [alertController addAction:self.okayAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

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

4. Now run the  code. And click the button. You will get the desired output.

No comments:

Post a Comment

Ads Inside Post

Blogger Widget