alertView:(UIAlertView *) alertView方法在Appdelegate中不工作



我在AppDelegate中设置了UIAlertView。m文件。

但是当我选择警报视图上的按钮时。

-(void) alertView:(UIAlertView *) alertView clickedButtonAtIndex:(NSInteger)buttonIndex

无法工作。

我已经在AppDelegate.h文件中设置了UIAlertViewDelegate。

和AppDelegate。m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:        (NSDictionary *)launchOptions
        {
         [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reachabilityChanged:)
                                                 name:kReachabilityChangedNotification
                                               object:nil];
            NSString *remoteHostName = REACHABILITY_HOST;
            _hostReachability = [Reachability reachabilityWithHostName:remoteHostName];
            [_hostReachability startNotifier];
            return YES;
        }
        - (void) reachabilityChanged:(NSNotification *)note
        {
         if( [Reachability isExistNetwork] == NotReachable)
            {
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil         message:@"my message" delegate:nil cancelButtonTitle:@"ok"         otherButtonTitles:@"set",nil];
                [alertView show];
            }
        }
        -(void) alertView:(UIAlertView *) alertView clickedButtonAtIndex:(NSInteger)buttonIndex
        {
            switch (buttonIndex) {
                case 0:
                    NSLog(@"ok!");
                    break;
                    // set
                case 1:
                    NSLog(@"set!");
                    NSURL*url=[NSURL URLWithString:@"prefs:root=WIFI"];
                    [[UIApplication sharedApplication] openURL:url];
                    break;
            }
        }

但是

-(void) alertView:(UIAlertView *) alertView clickedButtonAtIndex:(NSInteger)buttonIndex

未进入此方法。

有谁知道发生了什么事吗?谢谢。

您的代码没有正确设置警报视图的委托。

您需要更改以下行,以便委托是适当的对象(例如,self):

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil         message:@"my message" delegate:nil cancelButtonTitle:@"ok"         otherButtonTitles:@"set",nil];

你必须替换

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"my message" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:@"set",nil];
[alertView show];

这一行

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"my message" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:@"set",nil];
[alertView show];

你必须设置delegate为self来调用delegate方法

检查.h文件中的委托引用。戴上UIAlertViewDelegate

@interface YourViewController : UIViewController<UIAlertViewDelegate>

最新更新