我在UIImageView rDot中添加了一个tappershite。问题是,当我点击rDot时,什么都没有发生,而且它没有打印“I t worked”。rDot与其他元素在堆栈视图中,我不知道这是否与它不工作有关。rDot和redDot是两个独立的uiimageview。

 override func viewDidLoad() {
    super.viewDidLoad()

        rDot.isUserInteractionEnabled = true
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(rdotimageTapped(tapGestureRecognizer:)))
        rDot.addGestureRecognizer(tapGestureRecognizer)
}

func rdotimageTapped(tapGestureRecognizer: UITapGestureRecognizer) {
        whiteD?.isHidden = true
        redDot?.isHidden = false
        print("It worked")
    }

最佳答案

您需要将subView置于前面,因为您已将imageView置于stackView内。有时视图层次结构无法识别点击的subviews

override func viewDidLoad() {
    super.viewDidLoad()

    rDot.isUserInteractionEnabled = true
    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(rdotimageTapped(tapGestureRecognizer:)))
    rDot.addGestureRecognizer(tapGestureRecognizer)
    view.bringSubview(toFront: rDot)
}

10-07 16:18