iOS8之后UIAlertViewController的出现让我们不得不考虑在iOS7上的兼容问题

其实无非是做一下判断iOS8之前仍然用UIAlertView 之后用UIAlertViewController

关于UIAlertViewController

源码

  • 首先要说的是UIAlertControllerStyle这一属性

在头文件中

typedef NS_ENUM(NSInteger, UIAlertControllerStyle) {
  UIAlertControllerStyleActionSheet = 0,
  UIAlertControllerStyleAlert
} NS_ENUM_AVAILABLE_IOS(8_0);

这么一来,UIAlertController就等于是UIAlertViewUIActionSheet的合体了,只需要设置不同的style就可任意的切换要AlertView还是ActionSheet了
(ActionSheet这里先不说,这里主要说说UIAlertController替代UIAlertView的用法)。

  • 其次是继承关系

·

NS_CLASS_AVAILABLE_IOS(8_0) @interface UIAlertController : UIViewController

UIAlertController继承自UIViewController,那么注定它的用法和继承自UIViewUIAlertViewUIActionSheet不同,addSubView:的方法肯定是不能用了,在一个controller中想要呈现另一个controller,我首先想到的是模态

- (void)presentViewController:(UIViewController *)viewControllerToPresent animated: (BOOL)flag completion:(void (^ __nullable)(void))completion NS_AVAILABLE_IOS(5_0);

了解以上的基本信息,就可以开始尝试使用了

如何使用

//初始化
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您正在使用 UIAlertController" preferredStyle:UIAlertControllerStyleAlert];

//创建action 添加到alertController上 可根据UIAlertActionStyleDefault创建不通的alertAction
UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
    //回调
    // 模态视图,使用dismiss 隐藏
    [alertController dismissViewControllerAnimated:YES completion:nil];

}];
UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancle handler:^(UIAlertAction *action) {
    [alertController dismissViewControllerAnimated:YES completion:nil];

}];

//往alertViewController上添加alertAction
[alertController addAction:action1];
[alertController addAction:action2];

//呈现
[self presentViewController:alertController animated:YES completion:nil];

这里需要提一下UIAlertAction,它是随UIAlertViewController一起出现的,它的用法也很简单,看头文件就行了,不再赘述,但需要特别说明的是,UIAlertAction通过block回调使alert相关的代码变得紧凑,明了,不再像UIAlertView使用delegate把相关代码拆散。

补充

其实从上边可以看出使用UIAlertViewController是非常简单的,无非用的时候做一下兼容处理,为什么我还要写这么一段?因为有人懒。。。。

这里有一个工具类,做好了iOS8之前和之后的兼容

拿走不谢https://github.com/yongqianvip/iOS_DevTool

本文地址: http://yongqianvip.github.io/2015/05/10/uialertviewcontroller_base/