要能够创建和上面相同的对话框视图
var alertView = UIAlertView()
alertView.delegate = self
alertView.title = "标题"
alertView.message = "这个是UIAlertView的默认样式"
alertView.addButtonWithTitle("取消")
alertView.addButtonWithTitle("好的")
alertView.show()
您也可以通过更改UIAlertView
的alertViewStyle
属性来实现输入文字、密码甚至登录框的效果。
UIAlertView文本对话框
UIAlertView密码对话框
UIAlertView登录对话框
UIAlertViewDelegate
协议拥有响应对话框视图的按钮动作的回调方法。还有当文本框内容改变时,调用alertViewShouldEnableOtherButton:
方法可以让按钮动态地可用或者不可用。
要说明一点,苹果官方现在并不提倡在iOS 8中使用UIAlertView
,取而代之的是UIAlertController
。下面我们就来介绍UIAlertController
的使用方法。
在iOS 8中,UIAlertController
在功能上是和UIAlertView
以及UIActionSheet
相同的,UIAlertController
以一种模块化替换的方式来代替这两货的功能和作用。是使用对话框(alert)还是使用上拉菜单(action sheet),就取决于在创建控制器时,您是如何设置首选样式的。
您可以比较一下两种不同的创建对话框的代码,创建基础UIAlertController
的代码和创建UIAlertView
的代码非常相似:
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"标题" message:@"这个是UIAlertController的默认样式" preferredStyle:UIAlertControllerStyleAlert];
同创建UIAlertView
相比,我们无需指定代理,也无需在初始化过程中指定按钮。不过要特别注意第三个参数,要确定您选择的是对话框样式还是上拉菜单样式。
通过创建UIAlertAction
的实例,您可以将动作按钮添加到控制器上。UIAlertAction
由标题字符串、样式以及当用户选中该动作时运行的代码块组成。通过UIAlertActionStyle
,您可以选择如下三种动作样式:常规(default)、取消(cancel)以及警示(destruective)。为了实现原来我们在创建UIAlertView
时创建的按钮效果,我们只需创建这两个动作按钮并将它们添加到控制器上即可。
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:cancelAction];
[alertController addAction:okAction];
最后,我们只需显示这个对话框视图控制器即可:
[self presentViewController:alertController animated:YES completion:nil];
UIAlertController默认样式
按钮显示的次序取决于它们添加到对话框控制器上的次序。一般来说,根据苹果官方制定的《iOS 用户界面指南》,在拥有两个按钮的对话框中,您应当将取消按钮放在左边。要注意,取消按钮是唯一的,如果您添加了第二个取消按钮,那么你就会得到如下的一个运行时异常:
* Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘UIAlertController can only have one action with a style of UIAl