gpt4 book ai didi

ios - 在 UILabel 上添加关闭操作

转载 作者:搜寻专家 更新时间:2023-10-31 22:10:35 24 4
gpt4 key购买 nike

我想在用户点击 UILabel 时添加一个闭包:

class ActionLabel: UILabel {
typealias DidTapLabel = (ActionLabel) -> ()

private let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTouchUpInside(sender:)))

var didTouchUpInside: DidTapLabel? {
didSet {
if didTouchUpInside != nil {
self.addGestureRecognizer(tapGestureRecognizer)
self.isUserInteractionEnabled = true
} else {
self.removeGestureRecognizer(tapGestureRecognizer)
self.isUserInteractionEnabled = false
}
}
}

// MARK: - Actions
@objc func didTouchUpInside(sender: ActionLabel) {
if let handler = didTouchUpInside {
handler(self)
}
}
}

用法:

    label.didTouchUpInside = { [weak self] sender in
guard let strongSelf = self else {return}
print(strongSelf)
}

但是好像不行

最佳答案

您不能使用对 self 的引用来初始化手势识别器,因为此时初始化尚未完成。打印手势识别器数组显示 target 未设置的信息

addGestureRecognizer(tapGestureRecognizer)
print("\(gestureRecognizers)")

输出(看行尾)

Optional([<UITapGestureRecognizer: 0x6000001f9600; state = Possible; view = <asdfefe.ActionLabel 0x7fd714a03ea0>; target= <(action=didTouchUpInside:, target=<(null) 0x0>)>>])

因此,为了解决这个问题,您可以在初始化调用中初始化手势识别器

private var tapGestureRecognizer:UITapGestureRecognizer!

override init(frame: CGRect) {
super.init(frame: frame)
tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTouchUpInside))
}

希望对您有所帮助:)

关于ios - 在 UILabel 上添加关闭操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46972611/

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