问题
I have two UIAlertViews with ok/cancel buttons.
I catch the user response by:
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
The question I'm having is, which alertView is currently open?
I have different actions to do when clicking ok/cancel on each one...
回答1:
You have several options:
Use ivars. When creating the alert view:
myFirstAlertView = [[UIAlertView alloc] initWith...]; [myFirstAlertView show]; // similarly for the other alert view(s).
And in the delegate method:
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex { if (alertView == myFirstAlertView) { // do something. } else if (alertView == mySecondAlertView) { // do something else. } }
Use the
tag
property ofUIView
:#define kFirstAlertViewTag 1 #define kSecondAlertViewTag 2
UIAlertView *firstAlertView = [[UIAlertView alloc] initWith...]; firstAlertView.tag = kFirstAlertViewTag; [firstAlertView show]; // similarly for the other alert view(s).
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex { switch (alertView.tag) { case kFirstAlertViewTag: // do something; break; case kSecondAlertViewTag: // do something else break; } }
Subclass
UIAlertView
and add auserInfo
property. This way you can add an identifier to your alert views.@interface MyAlertView : UIAlertView @property (nonatomic) id userInfo; @end
myFirstAlertView = [[MyAlertView alloc] initWith...]; myFirstAlertView.userInfo = firstUserInfo; [myFirstAlertView show]; // similarly for the other alert view(s).
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex { if (alertView.userInfo == firstUserInfo) { // do something. } else if (alertView.userInfo == secondUserInfo) { // do something else. } }
回答2:
UIAlertView
is a UIView
subclass so you can use its tag
property for identification. So when you create alert view set its tag value and then you will be able to do the following:
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
if (alertView.tag == kFirstAlertTag){
// First alert
}
if (alertView.tag == kSecondAlertTag){
// First alert
}
}
来源:https://stackoverflow.com/questions/12731460/multiple-uialertviews-in-the-same-view