Domanda

I have an UIAlertView that is dismissed by a timer after a few seconds. Some users want to dismiss the alert view earlier simply by tapping the alert view itself.
I thus tried to add a single tap gesture recognizer to the alertView, but its action was not called. I then read on SO that the alert view must be in a view hierarchy before the gesture recognizer can be added. I am not sure about this but anyway I thus moved adding of the gesture recognizer to the alert view delegate method didPresentAlertView:, but the action is still not called.
Here is my code. Any help is appreciated.

The initialization of the alert view:

alertView = [[UIAlertView alloc] initWithTitle:@"title" message:@"message" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
}
[alertView performSelectorOnMainThread:@selector(show) withObject:self waitUntilDone:NO];
[self performSelector:@selector(dismissAlertAfterDelay:) withObject:alertView afterDelay:4.0];

The delegate method where the gesture recognizer is added:

- (void)didPresentAlertView:(UIAlertView *)alertView{
    alertView.userInteractionEnabled = YES;
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget: self action:@selector(dismissAlert:)];
    singleTap.numberOfTapsRequired = 1;
    [alertView addGestureRecognizer:singleTap];
}

and the action method that is NOT called:

-(void)dismissAlert:(UITapGestureRecognizer *)sender{
    UIAlertView *alertView = (UIAlertView *)sender.view;
    [alertView removeFromSuperview];
}

I know that an alert view is displayed in a separate window, but I believe anyway that a gesture recognizer added to it should call the action method when user interaction is enabled for the alert view.
Any suggestions?

È stato utile?

Soluzione

UIAlertView is, despite its name ending in View, a model class in iOS 7. It never gets added to the view hierarchy. That's why adding subviews to it doesn't work either: they are added, but their parent isn't in the view hierarchy. The view hierarchy that's presented when you show an alert is private and is not to be messed with.

I suggest following the HIG by just using a dismiss button. If you really, really want the entire alert to be able to be tapped, look at SDCAlertView. It's a UIAlertView clone I wrote that does act like an actual view.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top