gpt4 book ai didi

iphone - 如何禁用iPhone中的alertview按钮?

转载 作者:行者123 更新时间:2023-12-03 18:36:58 27 4
gpt4 key购买 nike

我的警报 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 设置按钮启用属性使用

将 textView 添加到警报中
  • (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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com