gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:56:46 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com