0

if I do like this

- (void)viewDidLoad {
    [super viewDidLoad];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"test" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil];
    [alert show];
}

// Called when a button is clicked. The red view and alert will be automatically dismissed after this call returns
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    [self showView];
}

// after animation ,this will work fine
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
//    [self showView];
}

- (void)showView {
    // Called when a button is clicked. The view will be automatically dismissed after this call returns
    UIView *view = [[UIView alloc] init];
    view.frame = CGRectMake(0, 0, 200, 200);
    view.backgroundColor = [UIColor redColor];
    view.center = CGPointMake([UIScreen mainScreen].bounds.size.width/2.0f, [UIScreen mainScreen].bounds.size.height/2.0f);
    //    [self.view.window addSubview:view]; //when i use this ,both of the two delegate methods works fine
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    [window addSubview:view];
}

Then the red view and alert will be automatically dismissed after alertView:clickedButtonAtIndex: call returns

enter image description here

who can show me the reason?

what's the difference between self.view.widow and [[UIApplication sharedApplication] keyWindow] in Objective-C

Community
  • 1
  • 1
ChenYilong
  • 8,543
  • 9
  • 56
  • 84

1 Answers1

0

Your question is essentially addressed here:

diffrence between [[[[UIApplication sharedApplication] delegate] window] and [[UIApplication sharedApplication].keyWindow?

To tie it back to your question, the UIAlertView gets presented in a system window, and it is this window that is the keyWindow while your alert is being shown. When the alert is dismissed, that window disappears, hence why your view disappears.

Assuming that self.view is a subview of the app's window (almost always the case), your view continues to display because the window itself continues to be displayed after the alert is dismissed.

Community
  • 1
  • 1
Jose
  • 106
  • 4
  • The last paragraph is not quite right. `self.view.window` is whatever window the view was added to. It could be the main app window. It could be a secondary window created and used by the app. It could be a system window. Most likely it is the app's main window but it doesn't have to be. – rmaddy Nov 22 '15 at 16:45
  • OP should clarify, but I assumed that the use of self.view in this particular example meant that the view was a view controller's view which was added to the app's window automatically. I have clarified my answer. – Jose Nov 22 '15 at 17:04