Swift 5:将函数发送给GestureRecognizer时更改标签错误

我想将诸如参数之类的函数发送到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)?

wydly443 回答:Swift 5:将函数发送给GestureRecognizer时更改标签错误

我已经解决了这个问题。 我这样更改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)")

    }

我将答案发布给大家,请多多关照。谢谢

本文链接:https://www.f2er.com/2936827.html

大家都在问