sai*_*jab 10 objective-c uitextfield ios uialertcontroller
我使用的是UIAlertController提出了一个对话UITextField和一个UIAlertAction按钮标记为"好".如何将多个字符(例如5个字符)输入到UITextField?中,如何禁用该按钮?
sou*_*ned 17
您可以为您的观察者添加UITextField:
[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
[textField addTarget:self action:@selector(alertControllerTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}
Run Code Online (Sandbox Code Playgroud)
但首先禁用您的按钮:
okAction.enabled = NO;
Run Code Online (Sandbox Code Playgroud)
然后在您指定的方法中验证它:
- (void)alertTextFieldDidChange:(UITextField *)sender {
UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
if (alertController) {
UITextField *someTextField = alertController.textFields.firstObject;
UIAlertAction *okAction = alertController.actions.lastObject;
okAction.enabled = someTextField.text.length > 2;
}
}
Run Code Online (Sandbox Code Playgroud)
Moh*_*eer 16
在头文件中添加以下属性
@property(nonatomic, strong)UIAlertAction *okAction;
Run Code Online (Sandbox Code Playgroud)
然后在您的viewDidLoad方法中复制以下代码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];
Run Code Online (Sandbox Code Playgroud)
还要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;
}
Run Code Online (Sandbox Code Playgroud)
这应该工作
基于soulshined的答案的Swift 3实现:
var someAlert: UIAlertController {
let alert = UIAlertController(title: "Some Alert", message: nil, preferredStyle: .alert)
alert.addTextField {
$0.placeholder = "Write something"
$0.addTarget(self, action: #selector(self.textFieldTextDidChange(_:)), for: .editingChanged)
}
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
let submitAction = UIAlertAction(title: "Submit", style: .default) { _ in
// Do something...
}
submitAction.isEnabled = false
alert.addAction(submitAction)
return alert
}
func textFieldTextDidChange(_ textField: UITextField) {
if let alert = presentedViewController as? UIAlertController,
let action = alert.actions.last,
let text = textField.text {
action.isEnabled = text.characters.count > 0
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7821 次 |
| 最近记录: |