iOS8 UIAlertController

一、基本使用

使用UIAlertController 需三步:
1.创建控制器并指定样式和参数.。
2.添加按钮addAction。
3.模态推出(底部或中间弹出)。

// 1\. 创建alert控制器并指定style:UIAlertControllerStyleAlert||UIAlertControllerStyleActionSheet 本文以   Alert为例展示
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"确定要操作?" message:@"操作后不可恢复" preferredStyle:UIAlertControllerStyleAlert];

// 2. 添加选项

[alertController addAction: [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
    NSLog(@"点击了取消");
}]];

[alertController addAction: [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
    NSLog(@"点击了确定");
}]];

// 3. 模态退出控制器

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

*如果选项添加超过两个,会竖向排列。

image
    ![image](http://upload-images.jianshu.io/upload_images/9374943-ab05683d5b38174a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

二、可添加输入框,可用作输入密码等功能,也可添加多个输入框(如用户名和密码)。
效果图:

image

*要对输入框中的文字进行监测,密码超过6位确定按钮才可点。
因为要对AlertController的成员进行监听,并且操作确定按钮,所以提两个全局变量。
UIAlertAction * _otherAction; //确定按钮
UIAlertController * _alertController; // 控制器

-(void)buttonClinck{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"输入密码" message:@"密码为开机密码" preferredStyle:UIAlertControllerStyleAlert];
_alertController = alertController;
[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.secureTextEntry = YES;

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTextFieldTextDidChangeNotification:) name:UITextFieldTextDidChangeNotification object:textField];
}];
__weak actionsheetController *Wself = self;
//blcok中使用self最好用copy弱指针self,虽然有些block是局部变量(self并不包含block),但为保险,告诫自己都用。

[alertController addAction: [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {

    [Wself remoteNotif];

}]];

    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {

    [Wself remoteNotif];

}];

    [alertController addAction: otherAction];

otherAction.enabled = NO;

_otherAction = otherAction;

//先将确定按钮设为不可点,在通知中当输入的密码大于n位数可以点

//推出控制器

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

}

-(void)remoteNotif{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTextFieldTextDidChangeNotification:) name:UITextFieldTextDidChangeNotification object:_alertController.textFields.firstObject];
}

-(void)handleTextFieldTextDidChangeNotification:(NSNotification *)notification{
UITextField *textFile = notification.object;
_otherAction.enabled = textFile.text.length>5?YES:NO;
}

至此完结,注意添加监听后要移除。
文章借鉴网络,怕忘了自己总结的。不对的地方,请提出。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容