UIAlertController的使用,代替UIAlertView和UIActionSheet

在iOS8以后,UIAlertView就开始被抛弃了。

取而代之是UIAlertController

以前是警示框这样写:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请输入用户名、密码和服务器" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];

        [alert show];

效果如图:

现在是这样写:

        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"请输入用户名、密码和服务器" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"点击了取消按钮");
        }];
        UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"点击了确定按钮");
        }];

        
        [alertController addAction:cancelAction];
        [alertController addAction:OKAction];

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

效果如图:

添加多个Action会自动向下排列

上面代码中再添加一个

UIAlertAction *DesAction = [UIAlertAction actionWithTitle:@"Destory" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {

            NSLog(@"点击了Destory按钮");

        }];



[alertController addAction:DesAction];

如果提示菜单中有“取消”按钮的话,那么它永远都会出现在菜单的底部

//冻结确定按钮
        OKAction.enabled = NO;

添加文本框

[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            textField.placeholder = @"Email";
            textField.keyboardType = UIKeyboardTypeEmailAddress;
        }];
[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            textField.placeholder = @"Password";
            textField.secureTextEntry = YES;
        }];

UIActionSheet也用这个取代了。。方法是在初始化的时候把类型改一下就OK。但是UIActionSheet是不能加文本框的!!

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"请输入用户名、密码和服务器" preferredStyle:UIAlertControllerStyleActionSheet];

P.S 用通知监听用户名和密码输入, 这里有篇介绍得很好的文章:

http://blog.csdn.net/lengshengren/article/details/39896037

 

原文地址:https://www.cnblogs.com/endtel/p/4765840.html