首页 > 解决方案 > UITapGestureRecognizer 不在 UILabel 上工作,但在父视图上工作

问题描述

视图层次结构是这样的,

- control (UIView)
 - container (UIView)
     - icon (UILabel)
     - label(UILabel)

如果我尝试在控件上添加 Tap 手势,它会完美运行。如果我尝试在任何其他项目上添加Tap 手势,它就不起作用。

isUserInteractionEnabled为每个元素启用。我还要求BringToFront每个元素。

我也尝试设置UIGestureRecognizerDelegate和检测Touch事件,它也没有检测到。

任何想法?

这是代码,

func setGesture() {
//        self.isUserInteractionEnabled = true
//        containerView.isUserInteractionEnabled = true
        label.isUserInteractionEnabled = true
//        exclamationMark.isUserInteractionEnabled = true

        self.bringSubview(toFront: containerView)
        containerView.bringSubview(toFront: exclamationMark)

        label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTapSavingLabel)))
        //exclamationMark.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTapExclamationMarkButton)))
        //self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(selfTapped)))
    }

    @objc func didTapExclamationMarkButton() {
        delegate?.didTapExclamationMarkButton()
    }

    @objc func didTapSavingLabel() {
        delegate?.didTapSavingLabel()
    }

    @objc func selfTapped() {
        print("Self Tapped")
    }

如果我取消注释 Self 上的 Tap 手势,效果很好。

标签: iosswiftxcode

解决方案


问题是标签的一个或多个超级视图的帧大小为0,0. 当该视图的.clipsToBounds属性为false时,它允许在屏幕上看到其子视图(在本例中为标签),但它会超出其父视图的范围。

这种情况下的任何视图都不会响应触摸/手势。

解决布局问题并正确设置框架后,添加到标签的点击手势将按预期工作。


推荐阅读