swift - 为什么 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 参数?这似乎是一个不必要的步骤,但我认为这可能是一种扫描代码以提示此功能由按钮触发的方法。
解决方案
您可以有一个处理程序负责处理多个操作
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 设计人员认为为您提供设计最能满足您需求的解决方案的灵活性是一个好主意。
所以,在大多数情况下,虽然我很欣赏这看起来很奇怪(尤其是当你可以使用闭包时),但我确实很欣赏有可用的信息来做出我自己的选择
推荐阅读
- reactjs - 在 antD select 中添加复选框
- elasticsearch - 如果所有值都等于给定参数,则 Elasticsearch 查询返回结果
- java - 出于某种原因,我的 Android 房间 DAO 插入在 Temi Robot 上不起作用
- python - 以一种形式创建多个对象 django
- java - 如何从嵌套的 LinkedHashMap 中获取数据
- docker - 【docker on wsl2】 E: gnupg, gnupg2 和 gnupg1 好像没有安装
- kubernetes - 如何设置适合我的应用程序的就绪和活跃度探测值?想避免为http探针编写代码
- vue.js - Nuxtjs 组合 API 反应式不适用于嵌套对象
- android - Andorid app dev - 读取连接的谷歌账户
- html - 调整统一 webgl 画布无响应的大小