Detect any tap outside the current view

前端 未结 2 1638
北海茫月
北海茫月 2021-01-04 05:49

Is there a way to detect any tap outside the current view? I unsuccessfully tried to implement something with the hitTest method but I am not sure to understand it well.

2条回答
  •  既然无缘
    2021-01-04 06:19

    What you have to do is, In touchesBegan you have to get the first touch object from the touches set and you have to check the location of that touch in a view(inside which you want to detect the touch).

    After you get the location of touch in View, you have to check whether your currentView(The view which you have to check whether tap was inside or outside).

    If currentView's frame contains the touch location, that means touch has occurred inside the view otherwise outside.

    override func touchesBegan(_ touches: Set, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
    
        let touch = touches.first
        guard let location = touch?.location(in: self.view) else { return }
        if !currentView.frame.contains(location) {
            print("Tapped outside the view")
        } else {
            print("Tapped inside the view")
        }
    }
    

    Hope it Helps!

提交回复
热议问题