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

joe*_*ivi 1 xcode objective-c ios swift ios9

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

Nil*_*Jha 5

试试这个代码。

//
//  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
Run Code Online (Sandbox Code Playgroud)

输入文本之前 输入文字后