github学习地址:https://github.com/potato512/SYSwiftLearning
// 方法1
let alertView = UIAlertView(title: alertTitle, message: alertMessage, delegate: nil, cancelButtonTitle: alertCancel)
alertView.show()
// 方法2
// 实例化时添加代理对象(注意添加协议)
let alertView = UIAlertView(title: alertTitle, message: alertMessage, delegate: self, cancelButtonTitle: alertCancel, otherButtonTitles: alertOK, "提示", "通告", "警告")
alertView.show()
// 添加协议 UIAlertViewDelegate
class ViewController: UIViewController, UIAlertViewDelegate {
override func viewDidLoad() {
...
}
...
}
// 实现协议方法
// MARK: UIAlertViewDelegate
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
let buttonTitle = alertView.buttonTitleAtIndex(buttonIndex)
if buttonTitle == alertCancel
{
print("你点击了取消")
}
else if buttonTitle == alertOK
{
print("你点击了确定")
}
else
{
print("你点击了其他")
}
}
// 方法3
// 1 实例化
let alertVC = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertControllerStyle.Alert)
// 2 带输入框
alertVC.addTextFieldWithConfigurationHandler {
(textField: UITextField!) -> Void in
textField.placeholder = "用户名"
}
alertVC.addTextFieldWithConfigurationHandler {
(textField: UITextField!) -> Void in
textField.placeholder = "密码"
textField.secureTextEntry = true
}
// 3 命令(样式:退出Cancel,警告Destructive-按钮标题为红色,默认Default)
let alertActionCancel = UIAlertAction(title: alertCancel, style: UIAlertActionStyle.Destructive, handler: nil)
let alertActionOK = UIAlertAction(title: alertOK, style: UIAlertActionStyle.Default, handler: {
action in
print("OK")
// 3-1 获取输入框的输入信息
let username = alertVC.textFields!.first! as UITextField
let password = alertVC.textFields!.last! as UITextField
print("用户名:\(username.text),密码:\(password.text)")
})
alertVC.addAction(alertActionCancel)
alertVC.addAction(alertActionOK)
// 4 跳转显示
self.presentViewController(alertVC, animated: true, completion: nil)
// 方法4
let alertView = UIAlertView()
alertView.title = "开始!"
alertView.message = "游戏就要开始,你准备好了吗?"
alertView.addButtonWithTitle("Ready Go!")
alertView.addButtonWithTitle("Cancel")
alertView.delegate = self
alertView.show()
// 注意添加协议 UIAlertViewDelegate
// 代理方法
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
print("click \(buttonIndex)")
}
方法1示例图
方法2示例图
方法3示例图
本文详细介绍了Swift中如何使用UIAlertView,包括创建警告对话框、添加按钮、响应用户操作等,并提供了具体的代码示例,帮助开发者理解其用法。

625

被折叠的 条评论
为什么被折叠?



