arrays - 函数中的闭包数组参数

标签 arrays swift function parameters closures

我需要创建一个接受按钮数组和闭包数组的函数。最后,我的目标是将数组中的操作附加到每个按钮,并在通知中设置每个按钮。这是我的功能:

func makeButtons(buttons: [UIButton], withActions actions: [() -> Void]){

    var bottomAnchor: NSLayoutYAxisAnchor?
    bottomAnchor = notificationView.bottomAnchor

    buttons.forEach({ (button) in
        button.actionHandle(controlEvent: .touchUpInside, action: actions[buttons.index(of: button)!])

        notificationView.addSubview(button)

        button.bottomAnchor.constraint(equalTo: bottomAnchor!, constant: -20).isActive = true
        button.rightAnchor.constraint(equalTo: notificationView.rightAnchor, constant: -20).isActive = true
        button.leftAnchor.constraint(equalTo: notificationView.leftAnchor, constant: 20).isActive = true
        button.heightAnchor.constraint(equalToConstant: 40).isActive = true

        bottomAnchor = button.topAnchor
    })
}

我确实使用了一个扩展来使用actionHandle()为UIButton目标添加一个闭包。我从堆栈上取下来的。就是这样:

extension UIButton {
    private func actionHandleBlock(action:(() -> Void)? = nil) {
        struct __ {
            static var action :(() -> Void)?
        }
        if action != nil {
            __.action = action
        } else {
            __.action?()
        }
    }

    @objc private func triggerActionHandleBlock() {
        self.actionHandleBlock()
    }

    func actionHandle(controlEvent control: UIControlEvents, action:@escaping () -> Void) {
        self.actionHandleBlock(action: action)
        self.addTarget(self, action: #selector(triggerActionHandleBlock), for: control)
    }
}

另外,这是我如何使用 make Buttons 函数:

func setButtonsWithAction(){
        let button1 = UIButton()
        let button2 = UIButton()

        addButtons(buttons: [button1, button2], withActions: [self.sayHi, self.sayGoodbye])
    }

func sayHi(){
            print("Hi there")
        }

func sayGoodbye(){
    print("Goodbye")
}

一切都设置好了,正如我想要的。然而,我面临的问题是,无论我单击哪个按钮,它都会执行闭包数组中的最后一个函数。因此,在这种情况下,无论我单击哪个按钮,它都会打印“再见”。 我需要的是:

click button1 -> print Hi
click button2 -> print Goodbye

这是什么问题,我似乎无法弄清楚。

最佳答案

这绝对应该为您指明方向。 让我知道事情的后续。

fileprivate func toolbarButton(title: String, closure: Selector ) -> UIButton {
    let button = UIButton(type: .system)
    button.setTitle(title, for: .normal)
    button.tintColor = .darkGray
    button.addTarget(self, action: closure, for: .touchUpInside)
    return button
}

像这样使用:

lazy var nearButton = toolbarButton(title: "Near Me", closure: #selector(handleToolButtonNear))

关于arrays - 函数中的闭包数组参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47724505/

相关文章:

javascript - 使用 javascript 测试是否单击/触发了一个功能,然后禁用另一个功能。

c - C 中的 Char 数组

ios - 如何在 swift 中使用 daniel gindi/图表库在饼图中显示百分比符号(IOS 图表)

ios - 设置是否没有观察模型属性的变化 - Swift

ios - 如何在 swift 4 中使用 API 解析 jsondata

swift - 如何让标题栏以编程方式显示在 NSWindow 中?

c++ - 在 vector 使用中找不到 fatal error

c++ - 函数返回机制 :Temporary object, R-Value, L-Value

php - 合并来自两个不同 MySql 查询的两个不同数组

java - 数组在 Java 中被具体化