首页 > 解决方案 > 将多个闭包作为参数快速传递给函数

问题描述

所以我试图将两个闭包传递给一个创建子视图的函数。将闭包作为参数并调用它们的函数的主要部分如下:

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

标签: swift

解决方案


问题是它actionHandle以某种方式静态工作,因此它将用最近的一项覆盖任何先前的分配。

您可以执行以下操作(这里没有完整的代码解决方案,只有伪代码):

  • 子类 UIButton
  • 添加一个实例变量来保存要执行的闭包
  • 添加一个实例(帮助程序)函数作为事件的目标,并在内部执行上面的闭包
  • 创建一个将要执行的闭包作为参数的函数。里面,
    • 使用提供的闭包分配您的实例变量
    • addTarget(_:action:for:)以你的辅助函数为目标调用

如果您想支持不同UIControlEvent的 s,则必须稍微改进这些步骤,也许通过使用将事件映射到闭包等的字典。


推荐阅读