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

在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 欢迎您的加入.

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值