当我在iOS中输入空的AlertView文本字段时,不应该关闭AlertViewController

时间:2016-08-10 11:53:47

标签: ios objective-c swift xcode ios9

我在AlertViewController中添加了一个文本字段。我没有在文本字段中输入任何内容并输入OK按钮意味着关闭警报视图。如何检查警报文本字段长度为零,以便禁用警报按钮操作。请帮帮我......

1 个答案:

答案 0 :(得分:4)

试试这段代码。

//
//  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