UIAlertController的使用方法

UIAlertController在IOS8中新加的,整合了UIAlertView和UIActionSheet两个控件code

UIAlertView和UIActionSheet在IOS9中已经废弃server

======================================================================事件

1.两种表现形式:UIAlertControllerStyle

UIAlertControllerStyleAlert
UIAlertControllerStyleActionSheet

2. UIAlertControllerStyleAlert(UIAlertView)

UIAlertView

//初始化UIAlertController
  UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"请输入message" preferredStyle:UIAlertControllerStyleAlert];

  //建立点击按钮
  UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        //添加点击事件
    }

    //添加按钮到UIAlertController
    [alert addAction:cancelAction];
    [alert addAction:okAction];

    [self presentViewController:alert animated:YES completion:nil];

此外,还能够在AlertView(仅限在当前模式,ActionSheet中不可用)中添加TextField,以下it

//在画面中添加TextField
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {

        //添加提示信息
        textField.placeholder = @"登录,添加了监听,输入少于5个字符";
        
        // 消息通知机制(KVO): 监听--注册通知
        [[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(textFileChange:) name:UITextFieldTextDidChangeNotification object:textField];
    }];

/** AlertView中TextField监听*/
-(void)textFileChange:(NSNotification *)notification{
    UITextField *textField = (UITextField *)notification.object;
    
    UIAlertController *alert = (UIAlertController *)self.presentedViewController;
    
    UITextField *listen = alert.textFields[1];
    UIAlertAction *action = alert.actions.lastObject;
    //若是textFiled的长度超过5个字符,最后一个default按钮点击不可
    action.enabled = (listen.text.length <= 5);
}

3. UIAlertControllerStyleActionSheet(UIActionSheet)

UIActionSheet

//初始化
    UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:@"UIAlertControllerStyleActionSheet" message:@"Switched" preferredStyle:UIAlertControllerStyleActionSheet];
    
    //建立按钮
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        //添加点击事件
    }];

    //添加按钮
    [actionSheet addAction:cancelAction];
    [actionSheet addAction:okAction];
    
    [self presentViewController:actionSheet animated:YES completion:nil];
相关文章
相关标签/搜索