swift中UIAlertView的使用

本文详细介绍了Swift中如何使用UIAlertView,包括创建警告对话框、添加按钮、响应用户操作等,并提供了具体的代码示例,帮助开发者理解其用法。

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示例图





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

番薯大佬

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值