Swift警告框带有“确定”和“取消”按钮:哪个按钮被点击了?

122

我在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()
}

我可能在错误地使用这些按钮,请指正,因为这对我来说都是新的东西。


将操作添加到UIAlertview按钮的方法(使用Swift iOS) - Mixaz
7个回答

356

如果您正在使用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)

4
在你的示例中,可以使用 UIAlertActionStyle.Cancel 而不是 .Default - Tristan Warner-Smith
如果我想在取消操作中什么都不做,我可以返回空吗? - Gabriel Rodrigues
当然,从技术上讲,在这个例子中我只是在记录日志。但是如果我移除了日志,那么我将什么都不做。 - Michael Wildermuth
6
当答案针对较新版本的Swift进行更新时,这非常棒。 - BlackTigerX
有人知道如何将辅助功能 ID 添加到“确定”和“取消”操作中吗? - Kamaldeep singh Bhatia
那么Swift 3和Swift 5之间的区别就是在print语句中多了一个制表符吗?xD - joe

25
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) - Deepak Ghadi

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

4

您可以通过使用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显示警报


2

点赞一下:)

步骤1:创建一个新的独立类

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

第二步:调用As
    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  
                }
            }

这里的ToastManager是什么? - Mahmoud Zinji
1
你可以在这里管理你的业务逻辑。我使用ToastManager类展示了自定义警告提示。 - Asfar Hussain Siddiqui

0

您可能想考虑使用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")

-1

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接