仅在验证输入后启用UIAlertController的UIAlertAction [英] Enable UIAlertAction of UIAlertController only after input is validated

查看:44
本文介绍了仅在验证输入后启用UIAlertController的UIAlertAction的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 UIAlertController 呈现一个带有 UITextField 和一个标有"Ok"的 UIAlertAction 按钮的对话框.在 UITextField 中输入许多字符(例如5个字符)之前,如何禁用按钮?

I am using a UIAlertController to present a dialog with a UITextField and one UIAlertAction button labeled "Ok". How do I disable the button until a number of characters (say 5 characters) are input into the UITextField?

推荐答案

在头文件中添加以下属性

Add following property in your header file

@property(nonatomic, strong)UIAlertAction *okAction;   

然后将以下代码复制到 ViewController

then copy the following code in your viewDidLoad method of your ViewController

self.okAction = [UIAlertAction actionWithTitle:@"OK"
                                         style:UIAlertActionStyleDefault
                                       handler:nil];
self.okAction.enabled = NO;

UIAlertController *controller = [UIAlertController alertControllerWithTitle:nil
                                                                    message:@"Enter your text"
                                                             preferredStyle:UIAlertControllerStyleAlert];

[controller addTextFieldWithConfigurationHandler:^(UITextField *textField) {

    textField.delegate = self;
}];

[controller addAction:self.okAction];
[self presentViewController:controller animated:YES completion:nil];

还在类中实现以下 UITextField 委托方法

Also implement the following UITextField delegate method in your Class

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    NSString *finalString = [textField.text stringByReplacingCharactersInRange:range withString:string];
   [self.okAction setEnabled:(finalString.length >= 5)];
   return YES;
}

这应该有效

这篇关于仅在验证输入后启用UIAlertController的UIAlertAction的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆