如何使用Swift iOS向UIAlertView按钮添加动作 [英] How to add an action to a UIAlertView button using Swift iOS
本文介绍了如何使用Swift iOS向UIAlertView按钮添加动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想添加OK按钮以外的其他按钮,它应该只是解除警报。
我希望其他按钮调用某个函数。
I want to add another button other than the "OK" button which should just dismiss the alert. I want the other button to call a certain function.
var logInErrorAlert: UIAlertView = UIAlertView()
logInErrorAlert.title = "Ooops"
logInErrorAlert.message = "Unable to log in."
logInErrorAlert.addButtonWithTitle("Ok")
如何在此警报中添加其他按钮,然后允许它在点击后调用一个函数,让我们说我们想要新的按钮来调用:
How do I add another button to this alert, and then allow it to call a function once clicks so lets say we want the new button to call:
retry()
推荐答案
Swifty方式是使用新的UIAlertController和闭包:
The Swifty way is to use the new UIAlertController and closures:
// Create the alert controller
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)
// Create the actions
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
UIAlertAction in
NSLog("OK Pressed")
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
UIAlertAction in
NSLog("Cancel Pressed")
}
// Add the actions
alertController.addAction(okAction)
alertController.addAction(cancelAction)
// Present the controller
self.presentViewController(alertController, animated: true, completion: nil)
Swift 3:
// Create the alert controller
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
// Create the actions
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
UIAlertAction in
NSLog("OK Pressed")
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) {
UIAlertAction in
NSLog("Cancel Pressed")
}
// Add the actions
alertController.addAction(okAction)
alertController.addAction(cancelAction)
// Present the controller
self.present(alertController, animated: true, completion: nil)
这篇关于如何使用Swift iOS向UIAlertView按钮添加动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文