简体   繁体   中英

UIAlertView doesn't open url?

I created an alert view with three buttons -"Sign Up","Donate","Cancel"- when u click on either sign up or donate, safari should open with the specific website. However when I open the app, and click any of the buttons, safari doesn't open or do anything and the buttons work as though they were different versions of the cancel button. Here is my code:

In BlahBlah.h:

@interface BlahBlah: UIViewController <UITextFieldDelegate, UIAlertViewDelegate> {
}
@end

In BlahBlah.m:

#define donate_tag 0
#import "BlahBlah.h"
@implementation BlahBlah
...
- (void) donate {
UIAlertView *alert2  = [[UIAlertView alloc] initWithTitle:@"Donate"
message:@"Function doesn't work yet :(" delegate:nil cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Sign Up",@"Donate",nil];
alert2.tag = donate_tag;
[alert2 show];
[alert2 release];
}
...
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

if(alertView.tag == donate_tag && buttonIndex == 1){
   [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.google.com"]];
  }
else if(alertView.tag == donate_tag && buttonIndex == 2){
   [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.yahoo.com"]];
  }
}
...
@end

You need to tell the alert who handles the actions of the buttons, that is to say, who is the " delegate " of the alert view.

Since everything related to the UIAlertView is within your " BlahBlah " view controller, after creating alert2, do something like this:

alert2.delegate = self;

or declare it in your UIAlertView instantiation:

UIAlertView *alert2  = [[UIAlertView alloc] initWithTitle:@"Donate" 
    message:@"Function doesn't work yet :(" delegate:self 
    cancelButtonTitle:@"Cancel" otherButtonTitles:@"Sign Up",@"Donate",nil];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM