在iOS8.0之后的UIAlertView和UIActionSheet的新写法

来源:互联网 发布:java中的finalize方法 编辑:程序博客网 时间:2024/05/16 12:03

在iOS8.0之后,苹果更新了UIAlertView和UIActionSheet的创建方法。在以前的版本中,这两个提醒用户的控件各自有自己的创建方法,但是在iOS8.0之后,使用了UIAlertController这个控制器类统一创建。不过之前的创建方法并没有在iOS8.0之后的版本中实效,依然可以正常使用。下边就记录下新的写法。

首先看苹果API的示例写法:

UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"My Alert"                               message:@"This is an alert."                               preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault   handler:^(UIAlertAction * action) {}]; [self presentViewController:alert animated:YES completion:nil];

在这个事例中,创建了一个alert,在他的类方法:
alertControllerWithTitle:message:preferredStyle:
中,preferredStyle定义了创建的提示框的类型,这是一个枚举值。可以选择不同的提示框样式.

示例中的第二个类:UIAlertAction则创建出了一个行为:用户点击不同的按钮,触发不同的事件。不过在示例中,并没有把这个行为添加给提示框,我们可以用:

- (void)addAction:(UIAlertAction *)action;

这个方法把行为添加给提示框。

下边是一个小demo:

 /*!         @brief  在iOS8.0之后,alert 和 action sheet的创建方式有了改变:由UIAlertController统一创建。过去的创建alert方法在ios8中依然可用.         @since         */                // 创建一个alert        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"Attention!" message:@"Your Device Haven't PhotoLibrary." preferredStyle:UIAlertControllerStyleAlert];        // 定义动作事件        UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {            NSLog(@"点击了ok按钮后的回调");        }];        // 给提示框添加动作时间        [alert addAction:action];        // 弹出提示框        [self presentViewController:alert animated:YES completion:nil];



1 0