UIAlertView首先不推荐使用IOS 9


108

我尝试了几种使用UIAlertController而不是UIAlertView的方法。我尝试了几种方法,但无法使警报措施起作用。这是我的代码,可以在IOS 8和IOS 9中正常工作,但是显示不推荐使用的标志。我在下面尝试了优雅的建议,但在这种情况下无法使其起作用。我需要提交我的应用程序,这是最后要解决的问题。感谢您提出任何其他建议。我是新手。

#pragma mark - BUTTONS ================================
- (IBAction)showModesAction:(id)sender {
NSLog(@"iapMade: %d", iapMade3);

// IAP MADE ! ===========================================
if (!iapMade3) {

    //start game here
    gamePlaysCount++;
    [[NSUserDefaults standardUserDefaults]setInteger:gamePlaysCount forKey:@"gamePlaysCount"];
    NSLog(@"playsCount: %ld", (long)gamePlaysCount);

    if (gamePlaysCount >= 4) {
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Basic"
                                                     message: THREE_PLAYS_LIMIT_MESSAGE
                                                    delegate:self
                                           cancelButtonTitle:@"Yes, please"
                                           otherButtonTitles:@"No, thanks", nil];
       [alert show];

        NSString *path = [[NSBundle mainBundle] pathForResource:@"cow" ofType:@"wav"];
        _pop =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
        [_pop play];
        [self dismissViewControllerAnimated:true completion:nil];

    } else {
        if (gamePlaysCount == 1)  {
            // Create & store the next 5 mins when player gets 3 more lives
            nextDateToPlay = [[NSDate date] dateByAddingTimeInterval:60*60*0.1];
            NSLog(@"CURRENT DATE: %@", [NSDate date]);
            NSLog(@"NEXT DAY: %@", nextDateToPlay);
            [[NSUserDefaults standardUserDefaults]setObject: nextDateToPlay    forKey:@"nextDateToPlay"];
            NSLog(@"nextDateToPlay: %@", nextDateToPlay);

            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Basic"
                                                           message:  THREE_PLAYS_LIMIT_MESSAGE2
                                                          delegate:self
                                                 cancelButtonTitle:@"Got it!"
                                                 otherButtonTitles:@"Start", nil];
            [alert show];
        } else {

            if (gamePlaysCount == 3)  {
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Basic"
                                                               message: THREE_PLAYS_LIMIT_MESSAGE3
                                                              delegate:self
                                                     cancelButtonTitle:@"Yep, I Know!"
                                                     otherButtonTitles:@"Start", nil];
                [alert show];
            }
        }
    }
}

}

// IAP NOT MADE =============================

#pragma mark - ALERTVIEW DELEGATE ============================

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

if ([[alertView buttonTitleAtIndex:buttonIndex] isEqualToString:@"Yes, please"]) {

    UIStoryboard *storyboard = self.storyboard;
    MenuViewController *svc = [storyboard instantiateViewControllerWithIdentifier:@"Store"];
    svc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:svc animated:YES completion:nil];

        }

}

1
问题不清楚。你想要什么?
Moucheg 2015年

在iOS 9中不推荐使用UIAlertView,而必须将UIAlertController与UIAlertControllerStyleAlert的preferredStyle一起使用。但是,当我使用UIAlertController方法时,警报不会显示。我尝试下面的解决方案,但仍警告视图不显示..谢谢你..
布克斯

好的。你能证明你做了什么,那是行不通的?
Moucheg 2015年

1
介绍完之后,您将调用[self dismissViewControllerAnimated:truecomplete:nil]; 这将关闭警报控制器
Adnan Aftab

1
从UIAlertController相当新的意义上来说,这是一个重要的问题,许多开发人员将担心过时。不合理的否决票对有效问题不利。那些对这个问题投反对票的人应该在编辑后更改投票。但是随后,获得“否决票”徽章的“不赞成投票的巨魔”无论如何都不会这样做。SO主持人应该有一种解决方法。
龙猫

Answers:


237

从iOS8开始,Apple提供了新UIAlertController类,您可以使用它来代替现已弃用的UIAlertView,它也已在弃用消息中指出:

不推荐使用UIAlertView。改用UIAlertController和UIAlertControllerStyleAlert的preferredStyle

所以你应该使用这样的东西

UIAlertController * alert = [UIAlertController
                alertControllerWithTitle:@"Title"
                                 message:@"Message"
                          preferredStyle:UIAlertControllerStyleAlert];



UIAlertAction* yesButton = [UIAlertAction
                    actionWithTitle:@"Yes, please"
                              style:UIAlertActionStyleDefault
                            handler:^(UIAlertAction * action) {
                                //Handle your yes please button action here
                            }];

UIAlertAction* noButton = [UIAlertAction
                        actionWithTitle:@"No, thanks"
                                  style:UIAlertActionStyleDefault
                                handler:^(UIAlertAction * action) {
                                   //Handle no, thanks button                
                                }];

[alert addAction:yesButton];
[alert addAction:noButton];

[self presentViewController:alert animated:YES completion:nil];

2
谢谢您的快速回复。.我尝试了此操作,但是没有显示警报视图。.当添加我的yes please操作时也没有显示。
Bux 2015年

您能告诉我您的代码,因为它对我而言工作正常,请确保您在主线程上执行此代码
Adnan Aftab

您可以在问题中添加代码,这样每个人都能看到更好吗
Adnan Aftab 2015年

嗨,我添加了可在IOS8和IOS9中使用的完整代码,但已标记为不赞成使用。我尝试了几种方法来实现您的代码,但警报未显示,并且打开商店ViewController的操作将不起作用。谢谢您的帮助。
2015年

我认为最好[alert dismissViewControllerAnimated:YES completion:nil];从动作处理程序中删除此行,因为没有此代码,警报会自动隐藏。而且,可能会错误地将代码放入不会执行的完成块中。干杯:)
stellz '16

21
//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];
}

如果要在NSObject类中使用此警报,则应使用以下方式:

-(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:^{
    }];
});
}

14

新实现的Swift版本是:

 let alert = UIAlertController(title: "Oops!", message:"your message", preferredStyle: .Alert)
 alert.addAction(UIAlertAction(title: "Okay.", style: .Default) { _ in })
 self.presentViewController(alert, animated: true){}

11

Xcode 8 + Swift

假设selfUIViewController

func displayAlert() {
    let alert = UIAlertController(title: "Test",
                                  message: "I am a modal alert",
                                  preferredStyle: .alert)
    let defaultButton = UIAlertAction(title: "OK",
                                      style: .default) {(_) in
        // your defaultButton action goes here
    }
    
    alert.addAction(defaultButton)
    present(alert, animated: true) { 
        // completion goes here
    }
}

如果自我是我们如何实现这一目标?
Subin K Kuriakose

一个视图在做业务逻辑上没有任何关系。重新考虑您的架构,以便控制器呈现视图(MVVM或MVC)
SwiftArchitect

6

使UIAlertController + AlertController类别为:

UIAlertController + AlertController.h

typedef void (^UIAlertCompletionBlock) (UIAlertController *alertViewController, NSInteger buttonIndex);

@interface UIAlertController (AlertController)

+ (instancetype)showAlertIn:(UIViewController *)controller
                  WithTitle:(NSString *)title
                    message:(NSString *)message
          cancelButtonTitle:(NSString *)cancelButtonTitle
          otherButtonTitles:(NSString *)otherButtonTitle
                   tapBlock:(UIAlertCompletionBlock)tapBlock;
@end

UIAlertController + AlertController.m

@implementation UIAlertController (NTAlertController)

+ (instancetype)showAlertIn:(UIViewController *)controller
                  WithTitle:(NSString *)title
                    message:(NSString *)message
          cancelButtonTitle:(NSString *)cancelButtonTitle
          otherButtonTitles:(NSString *)otherButtonTitle
                   tapBlock:(UIAlertCompletionBlock)tapBlock {

    UIAlertController *alertController = [self alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];

    if(cancelButtonTitle != nil) {

        UIAlertAction *cancelButton = [UIAlertAction
                                       actionWithTitle:cancelButtonTitle
                                       style:UIAlertActionStyleCancel
                                       handler:^(UIAlertAction *action)
                                       {
                                           tapBlock(alertController, ALERTACTION_CANCEL); // CANCEL BUTTON CALL BACK ACTION
                                       }];
        [alertController addAction:cancelButton];

    }

    if(otherButtonTitle != nil) {

        UIAlertAction *otherButton = [UIAlertAction
                                   actionWithTitle:otherButtonTitle
                                   style:UIAlertActionStyleDefault
                                   handler:^(UIAlertAction *action)
                                   {
                                       tapBlock(alertController, ALERTACTION_OTHER); // OTHER BUTTON CALL BACK ACTION
                                   }];

        [alertController addAction:otherButton];
    }

    [controller presentViewController:alertController animated:YES completion:nil];

    return alertController;
}

@end

在您的ViewController.m中

[UIAlertController showAlertIn:self WithTitle:@"" message:@"" cancelButtonTitle:@"Cancel" otherButtonTitles:@"Other" tapBlock:^(UIAlertController *alertController, NSInteger index){

 if(index == ALERTACTION_CANCEL){

 // CANCEL BUTTON ACTION
 }else
if(index == ALERTACTION_OTHER){

 // OTHER BUTTON ACTION
 }

 [alertController dismissViewControllerAnimated:YES completion:nil];

 }];

注意:如果要添加两个以上的按钮,则向UIAlertController添加另一个UIAlertAction。


3

使用UIAlertController而不是UIAlertView

-(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];
}

3

我尝试了上述方法,只有将presentViewController:方法放在dispatch_async句子中时,没人能显示警报视图:

dispatch_async(dispatch_get_main_queue(), ^ { [self presentViewController:alert animated:YES completion:nil]; });

请参阅iOS 9的UIAlertView的替代方法?


1
 UIAlertController * alert = [UIAlertController
                                 alertControllerWithTitle:@"Are you sure you want to logout?"
                                 message:@""
                                 preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction* yesButton = [UIAlertAction
                                actionWithTitle:@"Logout"
                                style:UIAlertActionStyleDestructive
                                handler:^(UIAlertAction * action)
                                {

                                }];

    UIAlertAction* noButton = [UIAlertAction
                               actionWithTitle:@"Cancel"
                               style:UIAlertActionStyleDefault
                               handler:^(UIAlertAction * action) {
                                   //Handle no, thanks button
                               }];

    [alert addAction:noButton];
    [alert addAction:yesButton];

    [self presentViewController:alert animated:YES completion:nil];

0

检查一下:

UIAlertController *alertctrl =[UIAlertController alertControllerWithTitle:@"choose Image" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *camera =[UIAlertAction actionWithTitle:@"camera" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self Action];  //call Action need to perform 
    }];

[alertctrl addAction:camera];
-(void)Action 

{

}

0
-(void)showAlert{

    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Title"
                                                                   message:"Message"
                                                            preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {}];

    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
}

[self showAlert]; //调用方法

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.