带有 OK 和 Cancel 的 Swift 警报视图:点击了哪个按钮?

Posted

技术标签:

【中文标题】带有 OK 和 Cancel 的 Swift 警报视图:点击了哪个按钮?【英文标题】:Swift alert view with OK and Cancel: which button tapped? 【发布时间】:2014-10-20 03:22:07 【问题描述】:

我在 Xcode 中有一个用 Swift 编写的警报视图,我想确定用户选择了哪个按钮(它是一个确认对话框)什么都不做或执行什么。

目前我有:

@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()

我可能用错了按钮,请纠正我,因为这对我来说是全新的。

【问题讨论】:

复制到***.com/questions/24195310/… 【参考方案1】:

如果您使用的是 ios8,则应该使用 UIAlertController — UIAlertView 是 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/

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)

【讨论】:

您可以在示例中使用UIAlertActionStyle.Cancel 而不是.Default 如果我想在取消操作中什么都不做,我可以什么都不返回? 当然,从技术上讲,我在示例中除了记录之外什么也没做。但是,如果我删除了日志,我将什么也不做。 为较新的 Swift 版本更新答案真是太棒了 任何人都知道如何将辅助功能 ID 添加到“确定”和“取消”操作【参考方案2】:
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)

【讨论】:

更新 Swift 5.3:refreshAlert.dismiss(animated: true, completion: nil)【参考方案3】:

您可以使用 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 Show Alert

【讨论】:

【参考方案4】:

为 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...!")

【讨论】:

【参考方案5】:

您可能需要考虑使用 SCLAlertView,替代 UIAlertViewUIAlertController

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

【讨论】:

【参考方案6】:

非常简单第 1 步:创建一个新类

    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)
    
    
    //Simple Alert view with button one
    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)
    
    
    //Simple Alert view with two button
    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)
    
    

第 2 步:调用为

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 
               
            else if tag == 1 
                
            
        

【讨论】:

【参考方案7】:

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)

【讨论】:

以上是关于带有 OK 和 Cancel 的 Swift 警报视图:点击了哪个按钮?的主要内容,如果未能解决你的问题,请参考以下文章

Swift:插入带有文本输入的警报框(和存储文本输入)

Xcode Swift 使用警报执行 segue

带有选项的 Swift IOS 7 通知警报

swift 带有确定按钮的警报视图

ios Swift 2:扩展 - 带有文本字段的警报

带有 label.text 值的 Swift 本地通知自定义警报声音