我的警报 View 有 2 个按钮“确定”和“取消”以及一个文本字段。 现在我想禁用“确定”按钮,直到用户在文本字段中输入一些文本。 我怎样才能做到这一点? 提前致谢
最佳答案
更新 2:适用于 Swift 5.1
<#your alert controller#>.addTextField {(tf) in
//... set your tf characteristics i.e .keyboardType here
NotificationCenter.default.addObserver(forName: UITextField.textDidChangeNotification,
object: tf,
queue: OperationQueue.main) { _ in
//enable or disable the selected action depending on whether the textField text is empty
<#your alert controller#>.actions[0].isEnabled = !tf.text!.isEmpty
}
}
发布此内容是为了更新 ios 5 以来的响应:
- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
UITextField *textField = [alertView textFieldAtIndex:0];
if ([textField.text length] == 0)
{
return NO;
}
return YES;
}
更新:iOS 8 以来,Apple 已弃用 UIAlertView,转而使用 UIAlertController。不再有对 alertViewShouldEnableFirstOtherButton:
的委托(delegate)调用
因此,您可以通过 UITextFieldTextDidChangeNotification
设置按钮启用属性
使用
- (void)addTextFieldWithConfigurationHandler:(void (^)(UITextField *textField))configurationHandler
[<#your alert#> addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.delegate = self;
textField.tag = 0; //set a tag to 0 though better to use a #define
}];
然后实现委托(delegate)方法
- (void)textFieldDidBeginEditing:(UITextField *)textField
- (void)textFieldDidBeginEditing:(UITextField *)textField{
//in here we want to listen for the "UITextFieldTextDidChangeNotification"
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(textFieldHasText:)
name:UITextFieldTextDidChangeNotification
object:textField];
}
当 textField 中的文本发生更改时,它将调用“textFieldHasText:”并传递 NSNotification*
-(void)textFieldHasText:(NSNotification*)notification{
//inside the notification is the object property which is the textField
//we cast the object to a UITextField*
if([[(UITextField*)notification.object text] length] == 0){
//The UIAlertController has actions which are its buttons.
//You can get all the actions "buttons" from the `actions` array
//we have just one so its at index 0
[<#your alert#>.actions[0] setEnabled:NO];
}
else{
[<#your alert#>.actions[0] setEnabled:YES];
}
}
完成后不要忘记删除你的观察者
关于iphone - 如何禁用iPhone中的alertview按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5101560/