首页 > 解决方案 > 为什么 UIAlertAction 的处理程序需要有一个引用 UIAlertAction 的参数?

问题描述

我正在使用一个简单的按钮,当按下该按钮时,它会运行我创建的功能。

最初,我是这样编写代码的:

func askQuestion() {
     // runs code to ask a question
}

@IBAction func buttonTapped(_ sender: UIButton) {
     let ac = UIAlertController(title: title, message: "You tapped the button.", preferredStyle: .alert)
     ac.addAction(UIAlertAction(title: "Continue", style: .default, handler: askQuestion))
    present(ac, animated: true)

但这会返回一个错误:

Cannot convert value of type '() -> ()' to expected argument type '((UIAlertAction) -> Void)?'

当您将以下参数添加到 askQuestion() 时,该问题已修复:

askQuestion(action: UIAlertAction! = nil)

为什么传递给 UIAlertAction 的处理程序方法要求它接受 UIAlertAction 参数?这似乎是一个不必要的步骤,但我认为这可能是一种扫描代码以提示此功能由按钮触发的方法。

标签: swiftsyntaxuibuttonhandleruialertaction

解决方案


您可以有一个处理程序负责处理多个操作

var continueAction: UIAlertAction!
var cancelAction: UIAlertAction!

override func viewDidLoad() {
    super.viewDidLoad()

    continueAction = UIAlertAction(title: "Continue", style: .default, handler: masterHandler)
    cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: masterHandler)
}

//...

 let ac = UIAlertController(title: title, message: "You tapped the button.", preferredStyle: .alert)
 ac.addAction(continueAction)
 ac.addAction(cancelAction)

就个人而言,我不知道您为什么会这样做,但 API 设计人员认为为您提供设计最能满足您需求的解决方案的灵活性是一个好主意。

所以,在大多数情况下,虽然我很欣赏这看起来很奇怪(尤其是当你可以使用闭包时),但我确实很欣赏有可用的信息来做出我自己的选择


推荐阅读