持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第28天,点击查看活动详情
大家好,我是小黑,一个还没秃头的程序员~~~
大家好,今天介绍的是如何使用UIAlertController实现警告框和操作表,效果如下:
话不多说,正文开始:
UIAlertController
UIAlertController可以向用户显示警报消息或者操作选项
使用该类可以配置警报和操作表,其中包含要显示的消息和要从中选择的操作。用你想要的动作和样式配置警报控制器之后,使用present(:animated:completion:)方法来显示它。UIKit在你的应用内容上以模式的方式显示警报和动作表。 除了向用户显示消息外,您还可以将操作与警报控制器相关联,从而为用户提供一种响应方式。对于使用addAction(:)方法添加的每个操作,警报控制器都会配置一个带有操作详细信息的按钮。
UIAlertController的基本属性如下:
| 属性 | 说明 |
|---|---|
| title | 警告的标题 |
| message | 警告的信息 |
| preferredStyle | 警报控制器的样式 |
UIAlertController设置属性的函数如下:
- addAction:将操作对象附加到警报或操作表
- actions:用户在响应警报或操作表时可以采取的操作
- preferredAction:用户从警报中采取的首选操作
- addTextField(configurationHandler:):向警报添加文本字段
- textFields:警报显示的文本字段数组
下面是一个简单的点击按钮弹出告警弹框的例子:
let buttonAlert = UIButton(type: UIButton.ButtonType.system)
buttonAlert.setTitle("测试告警框", for: .normal)
buttonAlert.frame=CGRect(x: 30, y: titleBarHeight+250, width: 100, height: 50)
buttonAlert.addTarget(self, action: #selector(showAlert), for: .touchUpInside)
self.view.addSubview(buttonAlert)
...
@objc func showAlert() {
NSLog("ajajajaj")
let alertController = UIAlertController(title: "温馨提示", message: "这是一个告警弹框", preferredStyle: .alert)
let okAction = UIAlertAction(title: "确定", style: .default) { (UIAlertAction) in
NSLog("点击确定")
}
let cancelAction = UIAlertAction(title: "取消", style: .cancel) { (UIAlertAction) in
NSLog("点击取消")
}
alertController.addAction(okAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true) {
NSLog("告警弹框关闭")
}
}
下面是一个简单的弹出操作选项框的例子:
let buttonAlertSheet = UIButton(type: UIButton.ButtonType.system)
buttonAlertSheet.setTitle("测试操作表", for: .normal)
buttonAlertSheet.frame=CGRect(x: 30+buttonAlert.frame.width, y: titleBarHeight+250, width: 100, height: 50)
buttonAlertSheet.addTarget(self, action: #selector(showAlertSheet), for: .touchUpInside)
self.view.addSubview(buttonAlertSheet)
...
@objc func showAlertSheet() {
let alertSheetController = UIAlertController()
let action1 = UIAlertAction(title: "选项1", style: .default) { (UIAlertAction) in
NSLog("选项1")
}
let action2 = UIAlertAction(title: "删除", style: .destructive) { (UIAlertAction) in
NSLog("选项2")
}
let cancelAction = UIAlertAction(title: "取消", style: .cancel) { (UIAlertAction) in
NSLog("点击取消")
}
alertSheetController.addAction(action1)
alertSheetController.addAction(action2)
alertSheetController.addAction(cancelAction)
self.present(alertSheetController, animated: true) {
NSLog("告警弹框关闭")
}
}
以上便是IOS中关于滑块控件UIAlertController的使用,今天的UIView学习分享就到这里,后面我会持续输出iOS开发笔记,感谢大家的阅读!共同努力!大家晚安!