代码之家  ›  专栏  ›  技术社区  ›  Emre Önder

TouchsStart总是返回错误的UIView

  •  0
  • Emre Önder  · 技术社区  · 7 年前

    我想检测我何时触摸到其他地方,而不是某个特定的位置 UIView .我在用 touchesBegan 然而,对于它来说,它总是打印“触摸在外面”(见下面的代码)。我错过了什么?

    我从这里得到了帮助 post .

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let hitView = self.view.hitTest(touch.location(in: self.view), with: event)
            if hitView === checkBackContainer {
                print("touch is inside")
            } else {
                print("touch is outside")
            }
        }
        super.touchesBegan(touches, with: event)
    }
    

    里面加了锚 ViewDidLoad 作用

    private lazy var checkBackContainer = ImageUploadContainerView()
    
    override func viewDidLoad(){
    self.view.addSubview(checkBackContainer)
    checkBackContainer.anchorCenterXToSuperview()
    checkBackContainer.topAnchor.constraint(equalTo: checkFrontContainer.bottomAnchor, constant: 20).isActive = true
    checkBackContainer.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 25).isActive = true
    checkBackContainer.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -25).isActive = true
    checkBackContainer.heightAnchor.constraint(equalTo: checkBackContainer.widthAnchor, multiplier: 0.42).isActive = true
    checkBackContainer.layer.applySketchShadow(color: UIColor.white, alpha: 1.0, x: 0, y: 0.33, blur: 1, spread: 0, cornerRadius: 6)
    
    let backTap = UITapGestureRecognizer(target: self, action: #selector(self.backContainerTapped(_:)))
    checkBackContainer.addGestureRecognizer(backTap) }
    

    编辑: ContainerView是一种习惯 UIView 其中有一些 UIStackView s UIlabel s和 UIImageView 它在里面。我发现这是因为一种习惯 UIView ,当我用常规的 UIView 1.它起作用了。

    1 回复  |  直到 7 年前
        1
  •  1
  •   KLD    7 年前

    尝试将UIGestureRecognizer添加到要在触摸时检测到的视图中:

    let tap = UITapGestureRecognizer(target: self, action: #selector(didTap(sender:)))
    view1.addGestureRecognizer(tap)
    view2.addGestureRecognizer(tap)
    
    @objc func didTap(sender: UITapGestureRecognizer) {
    //Perform whatever you want in here
    }
    

    或者,可以循环浏览父视图的所有子视图,并排除任何要排除的视图,如下所示:

    for view in self.view.subviews {
       if view != viewYouWantToExclude {
          view.addGestureRecognizer(tap)
       }
    }