iOS8新特性之---- UIAlertController解析

UIAlertController继承自 UIViewController, 也是一个控制器


 以前使用按钮(UIAlertView和UIActionSheet)
 UIAlertController 不管是要用 UIAlertView 还是 UIActionSheet 方式展示,都要以 title 和 message 参数来初始化.UIAlertView 会在当前显示的 view controller 中心以模态形式出现,UIActionSheet 则会在底部滑出。UIAlertView 可以同时有按钮和输入框,UIActionSheet 仅支持按钮。
 
 新的方式并没有把所有的 alert 按钮配置都放在初始化函数中,而是引入了一个新类 UIAlertAction 的对象,在初始化之后可以进行配置。这种形式的 API 重构让对按钮数量、类型、顺序方便有了更大的控制。同时也弃用了 UIAlertView 和 UIActionSheet 使用的delegate 这种方式,而是采用更简便的完成时回调。
#import "LoveViewController.h"
#import "NBViewController.h"
@interface LoveViewController ()
// 账号
@property (nonatomic,copy)  NSString *name;
// 密码
@property (nonatomic,copy)  NSString *passWord;
// 用来显示数据
@property (nonatomic,retain) UILabel *lable;
// 分段控件
@property (nonatomic,retain) UISegmentedControl *segment;
// 创建UIAlertControlle控件
@property (nonatomic,retain)  UIAlertController *alertController;
@end

 
@implementation LoveViewController
// 释放
- (void)dealloc{
    [_alertController release];
    [_segment release];
    [_lable release];
    [_passWord release];
    [_name release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor redColor];
#pragma mark     -------UIActionSheet------
   // [self createSheet];
#pragma mark     -------UIAlertView------
    // [self createAlertView];
#pragma mark      -------加载控件--------
    [self setUp];
    // 创建分段控件
    // 创建数组
    NSArray *itemArray = @[@"UCStyleAlert",@"UCStyleActionSheet"];
    self.segment = [[UISegmentedControl alloc]initWithItems:itemArray];
    self.segment.frame = CGRectMake(10, 30, 300, 40);
    // 默认选中项
    [self.segment setSelectedSegmentIndex:1];
    // 修改字体大小
    NSDictionary *dic = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:17],NSForegroundColorAttributeName:[UIColor whiteColor]};
    [self.segment setTitleTextAttributes:dic forState:(UIControlStateNormal)];
    // 设置宽度
    [self.segment setWidth:180 forSegmentAtIndex:1];
    [self.view addSubview:self.segment];
    [self.segment addTarget:self action:@selector(segmentCR:) forControlEvents:(UIControlEventValueChanged)];
    [self.segment release];
}
#pragma mark         --------响应 segment 的但是事件------------
- (void)segmentCR:(UISegmentedControl *)sender{
    switch (sender.selectedSegmentIndex) {
        case 0:
            // 1.UIAlertControllerStyleActionSheet样式
            // preferredStyle 希望用什么样式弹出   显示在屏幕中央
            // 两种样式  UIAlertControllerStyleActionSheet  (屏幕的底部);  UIAlertControllerStyleAlert(屏幕中央)
            self.alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"确认删除?" preferredStyle:(UIAlertControllerStyleActionSheet)];
            [self.alertController addAction:[UIAlertAction actionWithTitle:@"是,将本地数据一并删除" style:(UIAlertActionStyleDestructive) handler:^(UIAlertAction *action) {
                /**
                 1.三种样式
                 UIAlertActionStyleDefault = 0,    按钮应用标准样式。
                 UIAlertActionStyleCancel,      按钮应用取消样式,代表取消操作不做任何改变。
                 UIAlertActionStyleDestructive     按钮应用警示性的样式,提示用户这样做可能会改变或删除某些数据。
                 */
                // 单击按钮想要实现的操作
            }]];
            [self.alertController addAction:[UIAlertAction actionWithTitle:@"仅删除本地数据" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {
                NSLog(@"仅删除本地数据");
            }]];
            [self.alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction *action) {
                // 按钮想做的事情
                NSLog(@"点击了其他按钮");
            }]];
#warning mark   ----注意事项----
       /* {
          1.   reason: 'UIAlertController can only have one action with a style of UIAlertActionStyleCancel'
             同样的,向 alert 或 action sheet 添加一个以上的 .Cancel 按钮将会抛出异常:
           [self.alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction *action) {
                    NSLog(@"点击了其他按钮");
            }]];
      2.  如果试图向 alert controller 添加带有 .ActionSheet 样式的输入框,将会抛出异常:
        Terminating app due to uncaught exception NSInternalInconsistencyException, reason: 'Text fields can only be added to an alert controller of style UIAlertControllerStyleAlert'
        [self.alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.textColor = [UIColor redColor];

        }];
        } */
            // 模态方法弹出控制器(控制器显示的优先方法)
            [self presentViewController:self.alertController animated:YES completion:nil];
            break;
            
            
        {
            /** 获取文本框中输入的内容,并显示在 Lable 控件上(有两种方法)
             1.在外边设置两个属性值,用来接收
             2.使用数组的性质
             UITextField *login = alertC.textFields[0];
             UITextField *passWord = alertC.textFields[1];
             [self.view endEditing:YES];    // 获取文本内容,并隐藏键盘
             NSLog(@"登陆: %@,密码: %@",login.text,passWord.text);
             */
        }
        
            case 1:
        {
            // 1.UIAlertControllerStyleActionSheet样式
            // 如果创建的 UIAlertAction 不大于两个,并列显示;如果大于两个时,就会竖着显示.
          __block UIAlertController *alert= [UIAlertController alertControllerWithTitle:@"提示" message:@"支付" preferredStyle:(UIAlertControllerStyleAlert)];
            
            __block LoveViewController  *weakAlert = self;
            
            
            // 2.添加第一个按钮
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDestructive) handler:^(UIAlertAction *action) {
               
              weakAlert.lable.text = [[alert.textFields.firstObject text] stringByAppendingString:[alert.textFields.lastObject text]];
               NSLog(@"点击了确定按钮-----%@-----%@",[alert.textFields.firstObject text],[alert.textFields.lastObject text]);
            }]];
            // 3.添加第二个按钮
            [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction *action) {
                // 按钮想做的事情
                NSLog(@"点击了取消按钮");
            }]];
            //4. 添加第一个文本框
            // addTextFieldWithConfigurationHandler :添加文本框的配置,文字颜色,字体,阴影
            [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
                textField.textColor = [UIColor redColor];
                textField.placeholder = @"请输入账号";
                /**
                  监听文本框的修改
                  1.第一种方式 delagate 代理
                 
                  2.第二中方式  通知(点击确定,取消得到时候,alert就已经死了,通知就不起作用了)
                 再点击按钮的时候,就应该将 alert 移除,比较麻烦
                 {
                 // 如果需要监听 textField 开始,结束,改变状态,需要添加监听事件
                 [alertC addTextFieldWithConfigurationHandler:^(UITextField *textField) {
                 textField.placeholder = @"添加监听事件代码";
                 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alertTextFieldDidChange:) name:UITextFieldTextDidChangeNotification object:textField];
                 }];
                 - (void)alertTextFieldDidChange:(NSNotification *)notification{
                 UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
                 if (alertController) {
                 UITextField *listen = alertController.textFields[2];
                 UIAlertAction *action = alertController.actions.lastObject;
                 action.enabled = listen.text.length <= 5;
                 }
                 }
                 }
                  3.第三种方式(addTarget/action)  UIController(最好方式)
                 */
            
                #warning mark ----------第二种方法(显示文本框的内容)-----------
                   [textField addTarget:self action:@selector(textFieldChangedValue:) forControlEvents:(UIControlEventEditingChanged)];
              #warning mark    ----------第一种方法(显示文本框的内容)-----------
                  textField.delegate = self;
            }];
             // 5.添加文本框
            [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
                textField.secureTextEntry = YES;
                textField.placeholder = @"请输入密码";
            }];
#warning mark     -----监听文本框的修改------------
        {
            // 监听文本框的修改
            // 1.第一种方式 delagate 代理
            
            // 2.第二中方式  通知(点击确定,取消得到时候,alert就已经死了,通知就不起作用了)
            //再点击按钮的时候,就应该将 alert 移除,比较麻烦
            
            // 3.第三种方式(addTarget/action)  UIController(最好方式)
        }
            // 模态方法弹出控制器(控制器显示的优先方法)
            [self presentViewController:alert animated:YES completion:nil];
            break;
        }
        default:
        
            break;
       
    }
}
    
    
    
    
    
    
    
    
#pragma mark        --------监听文本框的改变------------
- (void)textFieldChangedValue:(UITextField *)username{
      NSLog(@"textField = %@",username.text);
#warning mark ----------第二种方法(显示文本框的内容)-----------
    self.lable.text = username.text;
}

#pragma mark    ---------实现文本代理的方法--------------
// 文本框是否可以结束编辑模式
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    return YES;
}
// 文本框已经结束编辑模式
- (void)textFieldDidEndEditing:(UITextField *)textField{
#warning mark    ----------第一种方法(显示文本框的内容)-----------
   // self.lable.text = textField.text;
}
// 文本框是否输入可以点击 Return 按钮
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];  //  取消第一个响应者
    return YES;
}


#pragma mark           --------创建控件用来演示------------
- (void)setUp{
    // 创建按钮
    self.lable = [[UILabel alloc]initWithFrame:CGRectMake(20, 100, 280, 40)];
    self.lable.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.lable];
    [self.lable release];
}
#pragma mark         ------UIActionSheet 操作----------
- (void)createSheet{
    /**
     UIActionSheet用来显示警示框,主要显示在屏幕的底部
     destructiveButtonTitle: 危险性的操作,摧毁性,就是操作具有危险性,修改性
     destructive 破坏的;毁灭性的;有害     cancel :消极的  取消;删去
     监听按钮的时候,需要进行操作,可以设置代理
     确定按钮式红色的,说明比较危险,  取消按钮跟其他按钮式分开的
     */
    // 创建对象
    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"提示"  delegate: nil cancelButtonTitle:@"取消" destructiveButtonTitle:@"确定" otherButtonTitles:@"关闭", nil];
    // 显示
    [sheet showInView:sheet];
UI
}
#pragma mark         ----------UIAlertView 操作---------------
- (void)createAlertView{
    // 创建对象
    UIAlertView *action = [[UIAlertView alloc]initWithTitle:@"提示" message:@"确认支付!!" delegate: self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    // 设置添加文本框的样式
    action.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
    // 根据索引查找文本框
    UITextField *textField = [action textFieldAtIndex:0];
    NSLog(@"%@",textField);// 返回对应的文本框
    // 显示
    [action show];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end

你可能感兴趣的:(UI,UIAlertView,UIActionSheet)