添加了新的类 UIAlertController 和 UIAlertAction 来取代曾经的 UIAlertView 和 UIActionSheet,感觉警告窗口的结构更容易理解了,使用起来也更简便。但是曾经用 Xcode 5 创建过 iOS 7程序在iOS 8 设备上运行就会出现各种问题。我清晰地记得刚刚升级 iOS 8 后连微信的警示操作表也出了问题,猜测可能是因此而起的。
下面来看看UIAlertController 和 UIAlertAction 用法:
1. 最简单的提醒视图:
这里我们实现一个最简单的提醒视图,包含1个标题,1行信息,1个按键,按下按键后,什么都不发生:
进入程序后,点击“Alert Me!”按钮可触发这个提醒框,如图所示:
从代码可以看出,新的API更加符合逻辑,有种需要什么就加什么的感觉。
2. 多个按键的提醒视图
这里我们实现一个最简单的提醒视图,包含1个标题,1行信息,3个按键,按下按键后,标签显示按下的按键名称:
3个按键分别代表了3种不同类型的按键,分别是默认按键(普通)、销毁按键(红色)和取消按键(粗体)。从代码看其实就是在上一个的基础上加了3个 UIAlertAction 而已,然后分别设置不同的 style,效果如下:
3. 带输入框的提醒视图
如何添加输入框呢?新的 iOS 8 提供了相应的接口,使增加输入框就像增加按键方法一样简单。这里还是在第1个方法的基础上改动。
在创建操作前先创建文本框,以便后面的按键可以操作文本框内容。创建文本框也只是用了一个简单的方法而已,想创建更多文本框就再使用多次这个方法即可,程序效果如下:
4. 提醒图表
与第2个和第3个方法相比,创建提醒图表简直易如反掌。因为和第1个方法相比,只需要改动一个参数就可以,即把创建UIAlertController实例的参数 UIAlertControllerStyleAlert 改为 UIAlertControllerStyleActionSheet ,别的都不用变。
这个就很简单了,跟第2个方法很像,效果如图:
5. 播放系统声音、提醒声音和振动设备
5. 播放系统声音、提醒声音和振动设备
在 iOS 8 中,调用声音的方法发生了小变化,用曾经的方式无法获取系统声音文件的 soundID 。因此,这里直接调用 soundID 值来调用对应的声音,注意振动仍然正常调用kSystemSoundID_Vibrate常量即可:
这样在 iOS 8 中就可以对用户发出提示了。