iOS弹出框主要由UIAlertController和UIAlertAction组成:
UIAlertController ——控制弹框显示的内容:属性title 和message 语义化不必多说,其中preferredStyle需注意
如果是页面中间的弹框则是.alert
如果是页面底部的弹框则是.actionsheet
UIAlertAction——点击按钮的交互行为,可以设置多个,声明完成后需要添加到UIAlertController中
示例如下:
1.自动关闭型
效果图:
代码:
@IBAction func toast(){
let alertToast = UIAlertController(title: "温馨提示", message: "恭喜您获得一张优惠券", preferredStyle: .alert)
present(alertToast, animated: true, completion: nil)
//一秒钟后自动消失
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
alertToast.dismiss(animated: false, completion: nil)
}
2.单按钮手动关闭
效果图:
代码:
@IBAction func singleButtonAlert(){
let alert=UIAlertController(title:"温馨提示",message:"恭喜您获得一张优惠券",preferredStyle:.alert)
let action=UIAlertAction(title:"我知道了",style:.default,handler:nil)
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
3.多按钮手动关闭
效果图:
如点击确定,会如下图打印
双按钮代码:
@IBAction func twoButtonAlert(){
let alert = UIAlertController(title:"温馨提示",message:"恭喜您获得一张优惠券",preferredStyle:.alert)
let cancel=UIAlertAction(title:"取消",style:.cancel)
let confirm=UIAlertAction(title:"确定",style:.default){(action)in
print("此处可以放其他操作如跳转页面")
}alert.addAction(cancel)
alert.addAction(confirm)
present(alert, animated: true, completion: nil)
}
三个按钮代码
@IBAction func threeButtonAlert(){
let alert = UIAlertController(title:"温馨提示",message:"恭喜您获得一张优惠券",preferredStyle:.alert)
let cancel=UIAlertAction(title:"取消",style:.cancel)
//cancel为加粗蓝色字
let confirm=UIAlertAction(title:"确定",style:.default)
//default为普通蓝色字
let destructive=UIAlertAction(title:"警告",style:.destructive)
//destructive为红色字
alert.addAction(cancel)
alert.addAction(confirm)
alert.addAction(destructive)
present(alert, animated: true, completion: nil)
}
4.多按钮带输入框手动关闭
效果图:
代码:
@IBAction func textFieldAlert(){
let alert = UIAlertController(title:"温馨提示",message:"请输入您的姓名",preferredStyle:.alert)
alert.addTextField(configurationHandler: {(textField)in
textField.placeholder="姓名"
textField.keyboardType = .default
})
let cancel=UIAlertAction(title:"取消",style:.cancel)
let confirm=UIAlertAction(title:"确定",style:.default){(action)in
print("此处可以放其他操作如跳转页面")
}
alert.addAction(cancel)
alert.addAction(confirm)
present(alert, animated: true, completion: nil)
}
5.底部弹窗
效果图:
代码:
@IBAction func onActionSheet(){
let actionSheet=UIAlertController(title:"温馨提示",message:"恭喜您获得一张优惠券",preferredStyle:.actionSheet)
let cancel=UIAlertAction(title:"取消",style:.cancel)
let confirm=UIAlertAction(title:"确定",style:.default)
actionSheet.addAction(cancel)
actionSheet.addAction(confirm)
present(actionSheet, animated: true, completion: nil)
}