Keep UIAlertView displayed

别说谁变了你拦得住时间么 提交于 2019-12-19 10:34:12

问题


I have a UIAlertView with a textField on it and two buttons: Save & Cancel. When the Save button is tapped I am checking if the text field isn't empty and after if it is I simply want to change the textFields placeholder to: @"enter a name please" and KEEP the alert view on screen. However it is automatically dismissed.

How do I override that?


回答1:


Add a target to the textfield in a subclassed alertView. You can subclass the alertView and not dismiss as described in this post

[[alertView textFieldAtIndex:0] addTarget:self action:@selector(textFieldDidChange) forControlEvents:UIControlEventEditingChanged];

Then write a function called textFieldDidChange that checks the current textfield of your alertView and set a boolean value so you know whether or not to dismiss the alert.

- (void) textFieldDidChange
{
  NSString *alertViewText = [[alertView textFieldAtIndex:0] text];

  if ([alertViewText isEqualToString:@""]) {
    [alertView setMessage:@"Enter a name please."];
  } else {
    [alertView setMessage:@"Default Message"];
  }
}

* Alternatively, I would suggest disabling "Save" when it is empty and not have to subclass. *

- (void) textFieldDidChange
{
  NSString *alertViewText = [[alertView textFieldAtIndex:0] text];

  if ([alertViewText isEqualToString:@""]) {
    [alertView setMessage:@"Enter a name please."];
    for (UIViewController *view in alertView.subview) {
       if ([view isKindOfClass:[UIButton class]]) {
          UIButton *button = (UIButton *)view;
          if ([[[button titleLabel] text] isEqualToString:@"Save"])
             [button setEnabled:NO];
       }      
    }
  } else {
    [alertView setMessage:@"Default Message"];
    for (UIViewController *view in alertView.subview) {
       if ([view isKindOfClass:[UIButton class]]) {
          UIButton *button = (UIButton *)view;
          if ([[[button titleLabel] text] isEqualToString:@"Save"])
             [button setEnabled:YES];
       }      
    }
  }
}


来源:https://stackoverflow.com/questions/9200616/keep-uialertview-displayed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!