我想将诸如参数之类的函数发送到gesturerecognizer,然后添加到UIlabel。所以我做了一个这样的功能:
final class ActionTag: NSObject {
var tag = 0
private let _action: (Int) -> ()
init(action: @escaping (Int) -> ()) {
_action = action
super.init()
}
@objc func action() {
_action(tag)
}
}
在我的职能中,我有一些代码:
for index in 0..<5 {
let dateLabel = UILabel()
dateLabel.tag = index + 1
addDoublePress(label: dateLabel, doubleTap: planDateDidDoubleTapped)
}
在此处定义:
private func addDoublePress(label: UILabel, doubleTap: ActionTag) {
label.isUserInteractionEnabled = true
doubleTap.tag = label.tag
let doubleTapRecognizer = UITapGestureRecognizer(target: doubleTap, action: #selector(doubleTap.action))
doubleTapRecognizer.numberOfTapsRequired = 2
label.addGestureRecognizer(doubleTapRecognizer)
}
private let planDateDidDoubleTapped = ActionTag { tag in
print("planDateDidDoubleTapped need implemention = \(tag)")
}
但是运行时,我得到的是:planDateDidDoubleTapped需要实现= 5为什么标签只保留一个值(5)?
我已经解决了这个问题。我像这样更改ActionTag类:
final class ActionTag: NSObject {
private let _action: (UITapGestureRecognizer) -> ()
init(action: @escaping (UITapGestureRecognizer) -> ()) {
_action = action
super.init()
}
@objc func action(sender: UITapGestureRecognizer) {
_action(sender)
}
}
我得到这样的标签:
private let planDateDidDoubleTapped = ActionTag { sender in
guard let tag = (sender.view as? UILabel)?.tag else { return }
print("planDateDidDoubleTapped need implemention = \(tag)")
}
我发布我的答案,请大家注意。谢谢