UIAlertView first deprecated IOS 9

后端 未结 10 1330
南笙
南笙 2020-11-28 02:29

I have tried several ways to use UIAlertController,instead of UIAlertView. I tried several ways but I cannot make the alert action work. Here is my code that works fine in I

10条回答
  •  广开言路
    2020-11-28 02:57

    //Calling     
    [self showMessage:@"There is no internet connection for this device"
                        withTitle:@"Error"];
    
    //Method
    
    -(void)showMessage:(NSString*)message withTitle:(NSString *)title
    {
    
     UIAlertController * alert=   [UIAlertController
                                      alertControllerWithTitle:title
                                      message:message
                                      preferredStyle:UIAlertControllerStyleAlert];
    
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
    
            //do something when click button
        }];
        [alert addAction:okAction];
        UIViewController *vc = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
        [vc presentViewController:alert animated:YES completion:nil];
    }
    

    If you want to use this alert in NSObject class you should use like:

    -(void)showMessage:(NSString*)message withTitle:(NSString *)title{
    dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    
        }]];
    
        [[[[UIApplication sharedApplication] keyWindow] rootViewController] presentViewController:alertController animated:YES completion:^{
        }];
    });
    }
    

提交回复
热议问题