在Xcode的iOS8 SDK中,UIAlertView和UIActionSheet都被UIAlertController取代。官方库解释:“UIAlertView is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead.”、“UIActionSheet is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleActionSheet instead.”。说明了在iOS8+开发,UIALertView和UIActionSheet已经过时了,UIAlertController以一种模块化替换的方式来代替这两这两个控件的功能和作用。如何创建及使用UIAlertController成为我们所关注的问题。
1、当前环境
Mac OS X EI Capitan
XCode 7.1 beta(7B60)
2、关键代码如下
-(void)alterTextFieldDidChange:(NSNotification*)notification {
UIAlertController *alertController = (UIAlertController*)self.presentedViewController;
if(alertController) {
UITextField *textfield = alertController.textFields[1];
//添加限制,如果输入长度在5个字节以内,则不允许点击最后一个按钮
UIAlertAction *action = alertController.actions.lastObject;
action.enabled = textfield.text.length >=5;
}
}
-(void)showAlertController {
//UIAlertController有2种属性,UIAlertControllerStyleAlert和 UIAlertControllerStyleActionSheet(不能添加editfield)
//(1)当样式为UIAlertControllerStyleAlert的时候,如果只有2个按钮并且"字一行够排"的话就水平排列,否则竖直排列
//(2)cancel按钮固定在最下面,其他按钮按添加顺序排列
UIAlertController *alertController = [UIAlertControlleralertControllerWithTitle:@"title"message:@"message"preferredStyle:UIAlertControllerStyleAlert];
//UIAlertActionStyleCancel 该风格字体颜色为蓝色加粗
UIAlertAction *UIAlertActionStyleCancelAction = [UIAlertActionactionWithTitle:@"UIAlertActionStyleCancel"style:UIAlertActionStyleCancelhandler:^(UIAlertAction *action) {
NSLog(@"UIAlertActionStyleCancel");
}];
//UIAlertActionStyleDefault 该风格字体颜色为蓝色
UIAlertAction *UIAlertActionStyleDefaultAction = [UIAlertActionactionWithTitle:@"UIAlertActionStyleDefault"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction *action) {
NSLog(@"UIAlertActionStyleDefault");
}];
//UIAlertActionStyleDestructive 该风格字体颜色红色(Destructive表示有破坏性的)
UIAlertAction *UIAlertActionStyleDestructiveAction = [UIAlertActionactionWithTitle:@"UIAlertActionStyleDestructive"style:UIAlertActionStyleDestructivehandler:^(UIAlertAction *action) {
NSLog(@"UIAlertActionStyleDestructive");
}];
[UIAlertActionStyleDestructiveAction setEnabled:NO];
[alertController addAction:UIAlertActionStyleCancelAction];
[alertController addAction:UIAlertActionStyleDestructiveAction];
[alertController addAction:UIAlertActionStyleDefaultAction];
//注意:需要添加textField的话,样式只能设为UIALertControllerStyleAlert
[alertController addTextFieldWithConfigurationHandler:^(UITextField * textField) {
textField.placeholder = @"用户名";
}];
[alertController addTextFieldWithConfigurationHandler:^(UITextField * textField) {
textField.placeholder = @"密码";
textField.secureTextEntry = YES;
[[NSNotificationCenter defaultCenter] addObserver:selfselector:@selector(alterTextFieldDidChange:)name:UITextFieldTextDidChangeNotificationobject:textField];
}];
[selfpresentViewController:alertController animated:YEScompletion:nil];
}
3、运行截图如下