// 两个控件:AlertController与AlertAction
import UIKit
class ViewController: UIViewController {
// AlertController是装AlertAction的
var alertController:UIAlertController!
overridefunc viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
alertController =UIAlertController(title:"提示", message:"You've got screwed!", preferredStyle: .alert)
// AlertController有两种状态。一个是 .alert,这种情况下,如果有1~2个 action,是这样的:
// 如果有大于2个action,是这样的:
// 另一类是 .actionSheet,是在屏幕底部的
下面介绍及添加 action
// 定义AlertAction,即一个选项
let alert1 =UIAlertAction(title: "OK", style: .cancel, handler:nil)
// 三种格式之 cancel: 粗体、蓝色,只能有一个,否则异常;default 蓝色普通字体;destructive 红色
let alert2 =UIAlertAction(title: "AFASDE", style: .default, handler:nil)
// 可以给 alertAction 加响应事件,即 handler:
let alert3 =UIAlertAction(title: "ABCOK", style: .destructive, handler: {
(a:UIAlertAction) in
self.view.backgroundColor =UIColor.gray
})
// 把action加到controller上:
alertController.addAction(alert1)
// 如果add的Action数量是0,则只显示UIAlertController的title和message, 如果action数量1或2,则横着显示,大于二就全竖着显示。注意,style为cancel的Action,不论添加顺序怎样,都是在最下面或最左面,不能改(一会介绍怎么自定义)。而其他的按照add的顺序排列。
alertController.addAction(alert3)
alertController.addAction(alert2)
// 此外,可以给 message下面那块区域添加一个文本框,可以输入文字
alertController.addTextField(configurationHandler: { // 配置文本框
(_text:UITextField) in
_text.text ="God Bless"
_text.textAlignment = .center
// _text.placeholder = "dswadsd"
})
// 获取文本框可以通过:alertController.textFields 获得文本框数组。
let button =UIButton(frame: CGRect(x:10, y: 300, width:50, height: 50))
button.backgroundColor =UIColor.blue
button.addTarget(self, action:#selector(function), for: .touchUpInside)
view.addSubview(button)
// 最后关于自定义颜色字体,有两种办法,靠谱的是 自己实现一个 alertController。第二种办法是,KVC 赋值,我们可以通过 runtime 取到 key,然后利用KVC赋值,这种办法并不好,因为封装好的系统控件最好别改,如果真的想用,可以参考这里http://www.jianshu.com/p/51949eec2e9c
}
func function(){
//注意 present方法不要写在viewDidLoad()里,不然无法present
present(alertController, animated:true, completion: nil)
}
}