UIAlertController是用来代替之前我们使用的UIAlertView和UIActionSheet,这次的改进总体来讲,感觉思路更清晰简洁了,使用起来也是颇为顺手,下面不多说老样子上代码:
-
#import "ViewController.h"
-
-
@interface ViewController ()
-
-
@end
-
-
@implementation ViewController
-
-
- (void)viewDidLoad {
-
[super viewDidLoad];
-
self.view.backgroundColor = [UIColor whiteColor];
-
-
[self alertViewcontrol];
-
// Do any additional setup after loading the view, typically from a nib.
-
}
-
-
-(void)alertViewcontrol
-
-
{
-
-
//UIAlertControllerStyleAlert
-
UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"司小文的博客" message:@"http://blog.****.net/siwen1990" preferredStyle:UIAlertControllerStyleAlert];
-
-
//UIAlertControllerStyleActionSheet
-
// UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"司小文的博客" message:@"http://blog.****.net/siwen1990" preferredStyle:UIAlertControllerStyleActionSheet];
-
-
-
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
-
//普通按钮
-
NSLog(@"我是普通按钮");
-
}];
-
-
UIAlertAction *aaaAction = [UIAlertAction actionWithTitle:@"aaa" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
-
//红色按键
-
NSLog(@"我是红色按键");
-
}];
-
-
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
-
//取消按钮
-
NSLog(@"我是取消按钮");
-
}];
-
-
-
//如果是UIAlertControllerStyleActionSheet 不能使用添加输入框的方法
-
[alertControl addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
-
//添加输入框(已经自动add,不需要手动)
-
-
textField.text = @"可以在这里写textfield的一些属性";
-
-
//监听
-
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(listeningTextField:) name:UITextFieldTextDidChangeNotification object:textField];
-
-
}];
-
-
//添加按钮(按钮的排列与添加顺序一样,唯独取消按钮会一直在最下面)
-
[alertControl addAction:okAction];//ok
-
[alertControl addAction:aaaAction];//aaa
-
[alertControl addAction:cancelAction];//cancel
-
-
//显示警报框
-
[self presentViewController:alertControl animated:YES completion:nil];
-
-
}
-
-
//监听弹框上的输入内容的变化
-
-(void)listeningTextField:(NSNotification *)notionfication
-
{
-
UITextField *thisTextField = (UITextField*)notionfication.object;
-
NSLog(@"%@",thisTextField.text);
-
}
-
-
- (void)didReceiveMemoryWarning {
-
[super didReceiveMemoryWarning];
-
// Dispose of any resources that can be recreated.
-
}
在UIAlertController中的显示方式有两种只是在创建时不同,其他的方法基本都是一样的
UIAlertControllerStyleAlert:(有输入框)

UIAlertControllerStyleActionSheet:(无输入框)

在UIAlertController可以添加的按钮总共有三类
UIAlertActionStyleDefault 普通
UIAlertActionStyleDestructive 红色
UIAlertActionStyleCancel 取消
主要记得,在改变UIAlertControllerStyleActionSheet的时候一定不要加上输入框,不然会崩溃呦~
本文为转载 原文地址:http://blog.****.net/siwen1990