UIAlertView 以及 UIAlertController

1.两者主要区别

  • UIAlertView可以在任意class中调用
    [alertView show];
  • UIAlertController只能在ViewContrller中调用
    [self presentViewController:alertVC animated:YES completion:nil];
  • UIAlertController对点击按钮的响应事件的处理比UIAlertView简单

2.UIAlertView的用法


#import "someExampleClass.h"


@interface someExampleClass ()
{
    NSString *someProperty;
}
@end

@implementation someExampleClass


- (void)createNewOrder {
    NSLog(@"创建新订单中...");
    
    UIAlertView *alt = [[UIAlertView alloc] initWithTitle:@"提示" message:@"创建新订单成功" delegate:self cancelButtonTitle:@"返回" otherButtonTitles:@"订单查看", nil];
    [alt show];
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSLog(@"click button at index: %ld", (long)buttonIndex);
    if (buttonIndex == 1) {
        // 点击按钮响应事件Here
    }
}

@end

3.UIAlertController的用法

UIAlertController *altVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"创建新订单成功" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"返回" style:UIAlertActionStyleCancel handler:nil];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"订单查询" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    // 按钮响应事件here
}];
[altVC addAction:cancelAction];
[altVC addAction:okAction];
[self presentViewController:alertVC animated:YES completion:nil];

4.在非VC class 中调用UIAlertController

在非VC class 中调用UIAlertController,还是要指定一个VC来present想要展示的UIAlertController

// 1.给window指定一个rootViewController
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor blackColor];
    [self.window makeKeyAndVisible];
    self.window.rootViewController = [[ViewController alloc] init];
    return YES;
}

// 2.任意地方展示UIAlertController
UIViewController *vc = [UIApplication sharedApplication].keyWindow.rootViewController;
[vc presentViewController:altVC animated:YES completion:nil];

你可能感兴趣的:(UIAlertView 以及 UIAlertController)