Swift-->UIAlertController(对话框)的使用

前端之家收集整理的这篇文章主要介绍了Swift-->UIAlertController(对话框)的使用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在IOS 8.0之后,UIAlertView 和 UIActionSheet 已经被废弃了. 取而代之的是UIAlertController

阅读之前,你需要具有Swift语法基础,至少要能看懂闭包以及结尾闭包.


下图是UIAlertControllerStyle.Alert (UIAlertView)样式的截图:

下图就是UIAlertControllerStyle.ActionSheet (UIActionSheet)样式的截图:

看了效果图,接下来就上代码了.

  1. //第一个参数是标题,第二个参数是消息内容,第三个参数就是上2张图中的样式,随便选一个.
  2. let alertViewController = UIAlertController(title: "title",message: "message",preferredStyle: .ActionSheet)
  3.  
  4. //如果没有调用addAction方法,对话框也是会显示的.但是没有可以点击的按钮.
  5. alertViewController.addAction(UIAlertAction(title: "title1",style: .Cancel,handler: { action in print("onAction") }))
  6.  
  7. //UIAlertAction的第二个参数是 按钮的样式(取消(粗体显示),消极(红色显示),正常)3种样式.
  8. //第三个参数是一个函数类型的参数. 表示点击按钮之后的调用方法.
  9. alertViewController.addAction(UIAlertAction(title: "title2",style: .Default,handler: { action in
  10. print("1")
  11. print("2")
  12. })
  13. )
  14. alertViewController.addAction(UIAlertAction(title: "title3",style: .Default) { action in
  15. print("11")
  16. print("22")
  17. }
  18. )
  19. alertViewController.addAction(UIAlertAction(title: "title4",style: .Destructive,handler: nil))
  20. //显示对话框
  21. self.presentViewController(alertViewController,animated: true,completion: nil)
  22. }

向对话框中添加文本框:效果

文本框可以添加多个

  1. alertViewController.addTextFieldWithConfigurationHandler({ textField in print(textField.text);textField.text = "angcyo1" })
  2. alertViewController.addTextFieldWithConfigurationHandler({ textField in print(textField.text);textField.text = "angcyo2" })
  3. alertViewController.addTextFieldWithConfigurationHandler({ textField in print(textField.text);textField.text = "angcyo3" })

获取文本框的内容:

  1. alertViewController.addAction(UIAlertAction(title: "title3",style: .Default) { action in
  2. print("textFields:\(alertViewController.textFields?[0].text)")
  3. print("textFields:\(alertViewController.textFields![1].text)")
  4. for textFields in alertViewController.textFields! {
  5. print("textFields:\(textFields.text)")
  6. }
  7. }
  8. )

需要注意的是: 文本框只能在 UIAlertControllerStyle.Alert 样式下,才能添加.否则会报异常.


至此: 文章就结束了,如有疑问: QQ群 Android:274306954 Swift:399799363 欢迎您的加入.

猜你在找的Swift相关文章