swift - 将多个闭包作为参数快速传递给函数
问题描述
所以我试图将两个闭包传递给一个创建子视图的函数。将闭包作为参数并调用它们的函数的主要部分如下:
///goButton and cancelButton are class level variables
var goButton = UIButton(type: .system)
var cancelButton = UIButton(type: .system)
func addSubViewWithAction(_ titleString:String, _ button1Text:String, _ button2Text:String, closureYes:@escaping ()->(), closureNo:@escaping ()->()) {
goButton.actionHandle(controlEvents: UIControlEvents.touchUpInside,
ForAction:closureYes)
cancelButton.actionHandle(controlEvents: UIControlEvents.touchUpInside,
ForAction:closureNo)
}
这就是我试图称呼它的方式。
addSubViewWithAction("Hide Penguin here?","Yes","Cancel", closureYes: switchPlayers, closureNo: deletePenquin)
问题是它为两个按钮调用了 deletePenguin 函数,而从不调用 switchPlayers 函数。
这是我如何通过子视图将按钮添加到主视图
//v here is a UIView object
//Add all buttons and text to subView
v.addSubview(titleField)
v.addSubview(goButton)
v.addSubview(cancelButton)
v.layer.cornerRadius = 8
//Add subView to main view
window.addSubview(v)
解决方案
问题是它actionHandle
以某种方式静态工作,因此它将用最近的一项覆盖任何先前的分配。
您可以执行以下操作(这里没有完整的代码解决方案,只有伪代码):
- 子类 UIButton
- 添加一个实例变量来保存要执行的闭包
- 添加一个实例(帮助程序)函数作为事件的目标,并在内部执行上面的闭包
- 创建一个将要执行的闭包作为参数的函数。里面,
- 使用提供的闭包分配您的实例变量
addTarget(_:action:for:)
以你的辅助函数为目标调用
如果您想支持不同UIControlEvent
的 s,则必须稍微改进这些步骤,也许通过使用将事件映射到闭包等的字典。
推荐阅读
- java - 为什么我的 fillRect 对一个有效,而对另一个无效?框架
- python - 使用“a”和“a+”打开不存在的文件与在附加之前手动检查它是否存在之间的区别
- macos - 从 Docker 运行 OpenModelica GUI 导致“无法连接到任何 X 显示器”错误
- python - 由于 sys arg 参数,Flask 应用程序忽略 cURL 请求的代码,但 sys arg 中没有传递任何内容
- ios - 当我从服务器获取时间时,为什么我的用户仍然能够操纵应用程序的时间?
- mongoose - 通过 NestJS 连接到 MongoDB 时注入记录器
- javascript - 不能在 firebase 中使用 array-contains-any。这是不可接受的值。为什么?
- vert.x - EBean 增强问题 [POJO 未增强]
- javascript - 在另一个数组中操作数组
- c# - Google API 支持 .NET 但不支持 Unity?