我正在使用UIAlertController来呈现一个带有UITextField的对话框和一个标有“Ok”的UIAlertAction按钮.如何在UITextField中输入多个字符(例如5个字符)之前禁用该按钮?
解决方法
在头文件中添加以下属性
@property(nonatomic,strong)UIAlertAction *okAction;
然后在ViewController的viewDidLoad方法中复制以下代码
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委托方法
- (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; }
这应该工作
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。