这里是第一篇文章,正如标题所说,我刚刚创建了一个显示 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)
}
最佳答案
两件事:
您不应退出应用。用户在使用完您的应用后会点击主页按钮。如果您调用
exit(0)
,就用户而言,这就是崩溃。警报不会阻塞。您的
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/