Swift -- 如何创建 UIAlertView 按钮点击或响应

标签 swift

这里是第一篇文章,正如标题所说,我刚刚创建了一个显示 2 个按钮的 UIAlertView,一个名为 yes,另一个名为 no。当我单击应用程序上的退出按钮时,会出现 UIAlertView。我想要做的是,如果我单击是按钮,应用程序退出,如果我单击否,它会保留。这是退出按钮的代码:我卡在了“if”部分。任何帮助将不胜感激!谢谢!

 @IBAction func Exit(sender: AnyObject) {
    let alert: UIAlertView = UIAlertView()
    alert.title = "Exit"
    alert.message = "Are you sure you want to exit?"
    let yesBut = alert.addButtonWithTitle("Yes")
    let noBut = alert.addButtonWithTitle("No")
    alert.show()

    if () {
        exit(0)
    }

最佳答案

两件事:

  1. 您不应退出应用。用户在使用完您的应用后会点击主页按钮。如果您调用 exit(0),就用户而言,这就是崩溃。

  2. 警报不会阻塞。您的 if 将在用户有机会响应您的警报之前发生。你需要让你的 ViewController 成为 UIAlertViewDelegate:

    class ViewController: UIViewController, UIAlertViewDelegate {
    

    并实现alertView:clickedButtonAtIndex:

    @IBAction func exitButton(sender: AnyObject) {
        let alert: UIAlertView = UIAlertView()
        alert.title = "Exit"
        alert.message = "Are you sure you want to exit?"
        let yesBut = alert.addButtonWithTitle("Yes")
        let noBut = alert.addButtonWithTitle("No")
        alert.delegate = self  // set the delegate here
        alert.show()
        println("This line doesn't wait for the alert to be responded to.")
    }
    
    func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
        let buttonTitle = alertView.buttonTitleAtIndex(buttonIndex)
        println("\(buttonTitle) pressed")
        if buttonTitle == "Yes" {
            // This is not recommended behavior.  The user will interpret this as a crash.
            exit(0)
        }
    }
    

注意:这仅用于演示目的。不建议根据按钮标题做出代码决定,因为如果您的应用程序已本地化(翻译成其他语言),这会中断。只需在 if 中使用 buttonIndex

关于Swift -- 如何创建 UIAlertView 按钮点击或响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27090327/

相关文章:

Swift - 我可以实现对类的相互泛型引用吗?

ios - 如何实现自定义键盘的设置包?

ios - 删除和替换 subview 时如何处理它们?

ios - NSURLDomainError 1005 "The Network Connection Was Lost"

swift - Kingfisher 是否支持视频缓存?

Swift 无法确定 switch 子句是否详尽无遗

Swift 使用 CloudKit 保存新评论

ios - 如何使用 couchbase 在 Swift 4 中通过数据库观察器检索数据?

swift - 为什么 xcode 尝试转换 googlemap cocoapods 框架?

ios - Swift CoreData 从 JSON 创建或更新实体