我正在使用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; }
这应该工作