Swift alert view with OK and Cancel: which button tapped?

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.

Currently I have:

@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.

185673 次浏览

如果使用 iOS8,则应使用 UIAlertController ーー UIAlertView 是 不赞成

下面是一个如何使用它的例子:

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/

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)

Swift 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)

Swift 5.3更新:

let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertController.Style.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)
var refreshAlert = UIAlertController(title: "Log Out", message: "Are You Sure to Log Out ? ", preferredStyle: UIAlertControllerStyle.Alert)


refreshAlert.addAction(UIAlertAction(title: "Confirm", style: .Default, handler: { (action: UIAlertAction!) in
self.navigationController?.popToRootViewControllerAnimated(true)
}))


refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction!) in


refreshAlert .dismissViewControllerAnimated(true, completion: nil)




}))


presentViewController(refreshAlert, animated: true, completion: nil)

您可以通过使用 UIAlertController 轻松实现这一点

let alertController = UIAlertController(
title: "Your title", message: "Your message", preferredStyle: .alert)
let defaultAction = UIAlertAction(
title: "Close Alert", style: .default, handler: nil)
//you can add custom actions as well
alertController.addAction(defaultAction)


present(alertController, animated: true, completion: nil)

.

参考资料: IOS 显示提醒

Updated for swift 3:

//函数定义:

@IBAction func showAlertDialog(_ sender: UIButton) {
// Declare Alert
let dialogMessage = UIAlertController(title: "Confirm", message: "Are you sure you want to Logout?", preferredStyle: .alert)


// Create OK button with action handler
let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
print("Ok button click...")
self.logoutFun()
})


// Create Cancel button with action handlder
let cancel = UIAlertAction(title: "Cancel", style: .cancel) { (action) -> Void in
print("Cancel button click...")
}


//Add OK and Cancel button to dialog message
dialogMessage.addAction(ok)
dialogMessage.addAction(cancel)


// Present dialog message to user
self.present(dialogMessage, animated: true, completion: nil)
}

//logoutFun ()函数定义:

func logoutFun()
{
print("Logout Successfully...!")
}

你可以考虑使用 SCLAlertView,作为 UIAlertView或者 UIAlertController的替代品。

UIAlertController 只能在 iOS 8.x 或更高版本上运行,SCLAlertView 是支持旧版本的一个很好的选择。

Github 查看详细信息

例如:

let alertView = SCLAlertView()
alertView.addButton("First Button", target:self, selector:Selector("firstButton"))
alertView.addButton("Second Button") {
print("Second button tapped")
}
alertView.showSuccess("Button View", subTitle: "This alert view has buttons")

Swift 的小更新5:

let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertController.Style.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")
}))


self.present(refreshAlert, animated: true, completion: nil)

点击更新投票:)

第一步: 创建一个新的独立类

import Foundation
import UIKit


class AppAlert: NSObject {
        

//Singleton class
static let shared = AppAlert()
        

//MARK: - Delegate
var onTapAction : ((Int)->Void)?
        

//Simple Alert view
public func simpleAlert(view: UIViewController, title: String?, message: String?){
ToastManager.show(title: title ?? "", state: .error)
}
        

//Alert view with Single Button
public func simpleAlert(view: UIViewController, title: String, message: String, buttonTitle: String) {
            

let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
//okButton Action
let okButton = UIAlertAction(title: buttonTitle, style: UIAlertAction.Style.default) {
(result : UIAlertAction) -> Void in
self.onTapAction?(0)
}
alert.addAction(okButton)
view.present(alert, animated: true, completion: nil)
}
        

//Alert view with Two Buttons
public func simpleAlert(view: UIViewController, title: String, message: String, buttonOneTitle: String, buttonTwoTitle: String){
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
            

//Button One Action
let buttonOne = UIAlertAction(title: buttonOneTitle, style: UIAlertAction.Style.default) {
(result : UIAlertAction) -> Void in
self.onTapAction?(0)
}
            

//Button Two Action
let buttonTwo = UIAlertAction(title: buttonTwoTitle, style: UIAlertAction.Style.default) {
(result : UIAlertAction) -> Void in
self.onTapAction?(1)
}
alert.addAction(buttonOne)
alert.addAction(buttonTwo)
view.present(alert, animated: true, completion: nil)
}
        

}

第二步: 调用 A

    AppAlert.shared.simpleAlert(view: self, title: "Register First", message: "Please Register to Proceed", buttonOneTitle: "Cancel", buttonTwoTitle: "OK")
AppAlert.shared.onTapAction = { [weak self] tag in
guard let self = self else {
return
}
if tag == 0 {
// DO YOUR WORK
} else if tag == 1 {
// DO YOUR WORK
}
}