函数中的闭包数组参数

时间:2017-12-09 01:46:35

标签: 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目标添加闭包。我从Stack上得到了它。就是这样:

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")
}

所有设置都正常,就像我想要的那样。但是,我遇到的问题是无论我点击哪个按钮,它都会执行闭包数组中的最后一个函数。因此,在这种情况下,无论我点击哪个按钮,它都会打印“Goodbye”。 我需要的是:

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

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

1 个答案:

答案 0 :(得分:0)

这绝对可以告诉你。 让我知道事情的后续。

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