iOS开发之UIAlertController

如果这篇文章帮助到了您,希望您能点击一下喜欢或者评论,你们的支持是我前进的强大动力.谢谢!

从ios8之后,系统的弹框 UIAlertView 与 UIActionSheet 两个并在一了起, 使用了一个新的控制器叫 UIAlertController

下面我就来介绍以下UIAlertController的简单使用

  • 1.UIAlertController的创建
/*
参数:
Title:显示的标题
message:标题底部显示的描述信息
preferredStyle:弹框的样式
    样式分为两种:UIAlertControllerStyleActionSheet
              : UIAlertControllerStyleAlert
*/
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"确定要退出嘛?" message:@“显示的信息" preferredStyle:UIAlertControllerStyleActionSheet]; 
  • 两种样式分别如下
iOS开发之UIAlertController_第1张图片
Snip20160302_9.png
  • 2.按钮的创建
    • 弹框当中的每一个按钮分别对应一个 UIAlertAction
    • UIAlertAction创建方式如下:
/*
参数:
actionWithTitle:按钮要显示的文字
style:按钮要显示的样式
      样式分为三种:
       UIAlertActionStyleDefault:默认样式,默认按钮颜色为蓝色 
       UIAlertActionStyleCancel:设置按钮为取消.点击取消时,会动退出弹框. 
                                注意:取消样式只能设置一个,如果有多个取消样式,则会发生错误.
       UIAlertActionStyleDestructive:危险操作按钮,按钮颜色显示为红色 
       handler:点击按钮时调用Block内部代码.
*/
                   
UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) { 
        NSLog(@"点击了取消"); 
}];

UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) { 
        NSLog(@"点击了确定"); 
        [self.navigationController popViewControllerAnimated:YES];
}];
  • 3.按钮的添加
//把创建的UIAlertAction添加到控制器当中:
[alertController addAction:action]; 
[alertController addAction:action1];
  • 除了添加按钮之外,还可以添加文本框
    • 添加文本框的前提是UIAlertController的样式必须得要是UIAlertControllerStyleAlert样式.否则会直接报错
    • 添加文本框方法为:
[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) { 
     textField.placeholder = @“文本框点位文字"; 
 }];
- 运行效果图:

     ![6080D576-7892-4C75-831F-0088AF2734B1.png](http://upload-images.jianshu.io/upload_images/1629728-fc905c0e2ff0dcd9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
- 通过控制器的textFields属性获取添加的文本框.注意textFields它是一个数组.
UITextField *textF =  alertController.textFields.lastObject;
  • 4.显示弹框.(相当于show操作)
[self presentViewController:alertController animated:YES completion:nil]; 

你可能感兴趣的:(iOS开发之UIAlertController)