Apple Combine 添加 TapPublisher 到 UIView

Apple Combine add TapPublisher to UIView

我可以将点击发布器添加到 UIView 或 UILabel 吗? UIButton 内置了 tapPublisher。我尝试进行扩展,但扩展无法存储属性。

此外,尝试在非按钮的任何内容上使用点击发布器是否是一种不良做法?

    func bindViewModel() {
        cancellables = [
            continueButton.tapPublisher.sink { [unowned self] in
                viewModel.action
                    .send(.question)
            },
            headlineLabel.tapPublisher.sink {
                // Error: "Value of type 'UILabel' has no member 'tapPublisher'..."
            })
        ]
    }

实际上 UIButton 没有内置它。我建议您使用 Building custom Combine publishers in Swift

的扩展

对于按钮来说很清楚,在里面你只需订阅 .touchUpInside 操作。

但是对于 UILabelUIView 就不是那么清楚了:你必须添加你的手势识别器,如果你已经添加了它,请确保你不会再添加一个。

您可以查看 gestureRecognizers,但仍有可能您尝试订阅的不是您的 gestureRecognizer。您可以将您的存储在 associated object 中,但这不是性能方面的最佳解决方案。

对于UILabel,您还需要开启userInteractionEnabled

我会说这对于扩展来说太合乎逻辑了,但这取决于你。