在IOS 8.0之后,UIAlertView 和 UIActionSheet 已经被废弃了. 取而代之的是UIAlertController
阅读之前,你需要具有Swift语法基础,至少要能看懂闭包以及结尾闭包.
下图是UIAlertControllerStyle.Alert (UIAlertView)样式的截图:
下图就是UIAlertControllerStyle.ActionSheet (UIActionSheet)样式的截图:
- //第一个参数是标题,第二个参数是消息内容,第三个参数就是上2张图中的样式,随便选一个.
- let alertViewController = UIAlertController(title: "title",message: "message",preferredStyle: .ActionSheet)
-
- //如果没有调用addAction方法,对话框也是会显示的.但是没有可以点击的按钮.
- alertViewController.addAction(UIAlertAction(title: "title1",style: .Cancel,handler: { action in print("onAction") }))
-
- //UIAlertAction的第二个参数是 按钮的样式(取消(粗体显示),消极(红色显示),正常)3种样式.
- //第三个参数是一个函数类型的参数. 表示点击按钮之后的调用的方法.
- alertViewController.addAction(UIAlertAction(title: "title2",style: .Default,handler: { action in
- print("1")
- print("2")
- })
- )
- alertViewController.addAction(UIAlertAction(title: "title3",style: .Default) { action in
- print("11")
- print("22")
- }
- )
- alertViewController.addAction(UIAlertAction(title: "title4",style: .Destructive,handler: nil))
- //显示对话框
- self.presentViewController(alertViewController,animated: true,completion: nil)
- }
文本框可以添加多个
- alertViewController.addTextFieldWithConfigurationHandler({ textField in print(textField.text);textField.text = "angcyo1" })
- alertViewController.addTextFieldWithConfigurationHandler({ textField in print(textField.text);textField.text = "angcyo2" })
- alertViewController.addTextFieldWithConfigurationHandler({ textField in print(textField.text);textField.text = "angcyo3" })
- alertViewController.addAction(UIAlertAction(title: "title3",style: .Default) { action in
- print("textFields:\(alertViewController.textFields?[0].text)")
- print("textFields:\(alertViewController.textFields![1].text)")
- for textFields in alertViewController.textFields! {
- print("textFields:\(textFields.text)")
- }
- }
- )
需要注意的是: 文本框只能在 UIAlertControllerStyle.Alert 样式下,才能添加.否则会报异常.
至此: 文章就结束了,如有疑问: QQ群 Android:274306954 Swift:399799363 欢迎您的加入.