如何在iPhone中禁用alertview的按钮?

dks*_*725 7 iphone uialertview

我有2个按钮"确定"和"取消"以及文本字段的警报视图.现在我要禁用"确定"按钮,直到用户在文本字段中输入一些文本.我怎样才能做到这一点?提前致谢

Rya*_*TCB 37

仅发布此内容以更新自ios 5以来的响应:

- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
  UITextField *textField = [alertView textFieldAtIndex:0];
  if ([textField.text length] == 0)
  {
    return NO;
  }
  return YES;
}
Run Code Online (Sandbox Code Playgroud)

更新:iOS 8由于Apple已弃用UIAlertView而不赞成使用UIAlertController.不再有代表电话alertViewShouldEnableFirstOtherButton:

因此,您可以通过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
}];
Run Code Online (Sandbox Code Playgroud)

然后实现委托方法

  • (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];

}
Run Code Online (Sandbox Code Playgroud)

当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];
}
}
Run Code Online (Sandbox Code Playgroud)

完成后不要忘记删除你的观察者

  • 我希望我能不止一次投票.非常感谢. (2认同)

EXC*_*ESS 1

您可以创建两个按钮“确定”和“取消”。然后将这两个按钮添加为 UIAlertView 中的子视图。现在通过检查文本字段中的文本(文本长度),您可以执行启用和禁用操作。