带有“确定”和“取消”的快速警报视图:轻按了哪个按钮? [英] Swift alert view with OK and Cancel: which button tapped?
问题描述
我有一个用Swift编写的Xcode警报视图,我想确定用户选择了哪个按钮(这是一个确认对话框),不执行任何操作或执行某些操作。
I have an alert view in Xcode written in Swift and I'd like to determine which button the user selected (it is a confirmation dialog) to do nothing or to execute something.
当前我有:
@IBAction func pushedRefresh(sender: AnyObject) {
var refreshAlert = UIAlertView()
refreshAlert.title = "Refresh?"
refreshAlert.message = "All data will be lost."
refreshAlert.addButtonWithTitle("Cancel")
refreshAlert.addButtonWithTitle("OK")
refreshAlert.show()
}
我可能使用了错误的按钮,请纠正我,因为这对我来说是全新的。
I'm probably using the buttons wrong, please do correct me since this is all new for me.
推荐答案
如果您使用的是iOS8,则应该使用UIAlertController-UIAlertView是已弃用。
If you are using iOS8, you should be using UIAlertController — UIAlertView is deprecated.
以下是使用它的示例:
var refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.Alert)
refreshAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
print("Handle Ok logic here")
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action: UIAlertAction!) in
print("Handle Cancel Logic here")
}))
presentViewController(refreshAlert, animated: true, completion: nil)
如您所见,UIAlertAction的块处理程序处理了按钮的按下。这里有个很棒的教程(尽管本教程不是使用swift编写的):
http:/ /hayageek.com/uialertcontroller-example-ios/
As you can see the block handlers for the UIAlertAction handle the button presses. A great tutorial is here (although this tutorial is not written using swift): http://hayageek.com/uialertcontroller-example-ios/
Swift 3更新:
let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.alert)
refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
print("Handle Ok logic here")
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
print("Handle Cancel Logic here")
}))
present(refreshAlert, animated: true, completion: nil)
迅速5更新:
let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.alert)
refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
print("Handle Ok logic here")
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
print("Handle Cancel Logic here")
}))
present(refreshAlert, animated: true, completion: nil)
这篇关于带有“确定”和“取消”的快速警报视图:轻按了哪个按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!