1.簡介:
在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+開發(fā)惑艇,UIALertView和UIActionSheet已經(jīng)過時了,UIAlertController以一種模塊化替換的方式來代替這兩這兩個控件的功能和作用院峡。
2.類型:
preferredStyle風(fēng)格樣式有兩種:UIAlertControllerStyleAlert和UIAlertControllerStyleActionSheet,是分別代表要代替的UIAlertView和UIActionSheet
3.顯示UIAlertController
1系宜、UIAlertController繼承于UIViewController照激;
2、顯示需要使用UIViewController的方法:presentViewController 彈出視圖控制器盹牧。
4.添加按鈕到UIAlertController
1俩垃、創(chuàng)建UIAlertAction作為UIAlertController的按鈕項;
2汰寓、初始化使用方法了:actionWithTitle: style: handler:口柳;
3、設(shè)置Title有滑、 style跃闹、handler(是一個閉包);
4毛好、添加 UIAlertAction至UIAlertController望艺。
5.添加文本輸入框
1、 文本輸入框只能添加到Alert的風(fēng)格中肌访,ActionSheet是不允許的荣茫;
2、UIAlertController具有只讀屬性的textFields數(shù)組场靴,需要可直接按自己需要的順序添加啡莉;
3港准、添加方式是使用block,參數(shù)是UITextField咧欣;
4浅缸、添加UITextField監(jiān)聽方法和實現(xiàn)方法
具體代碼如下
//1.創(chuàng)建一個UIAlertController選擇風(fēng)格樣式
let alertView2 = UIAlertController.init(title: "結(jié)束", message: "是否重來", preferredStyle: UIAlertControllerStyle.Alert)
//2.區(qū)別 Style :顯示在屏幕正中央
// ActionSheet: 顯示在屏幕最底部的中央
//3.顯示UIAlertController
self.presentViewController(alertView2, animated: true, completion: nil)
//4.添加按鈕到UIAlertController
let action = UIAlertAction.init(title: "取消", style: UIAlertActionStyle.Cancel) { (nil) in
}
let action2 = UIAlertAction.init(title: "默認(rèn)", style: UIAlertActionStyle.Default) { (nil) in
}
let action3 = UIAlertAction.init(title: "重置", style: UIAlertActionStyle.Destructive) { (nil) in
}
alertView2.addAction(action)
alertView2.addAction(action2)
alertView2.addAction(action3)
//5.添加文本輸入框
//添加文本輸入框,以登錄魄咕、密碼為例
alertView2.addTextFieldWithConfigurationHandler { (textField :UITextField) in
textField.placeholder = "登錄"
}
alertView2.addTextFieldWithConfigurationHandler { (textField :UITextField) in
textField.placeholder = "密碼"
textField.secureTextEntry = true
}
```
運(yùn)行結(jié)果如下:
![result.png](http://upload-images.jianshu.io/upload_images/2670926-eae70eee10b5538c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)