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

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

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

试试这个代码。

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