Search code examples
iosswiftxcodeuikittouch

touchesMoved touches.first!.view remains the same, if I move a finger out of view


I have a problem with touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) function. More specifically - touches.first!.view property. I need to know the tag of view that user is pointing at. But when I drag finger out of view bounds, touches.first!.view value does not change.

This is what I am doing: enter image description here

I have this code to print out selected view's tag and background color:

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    print("\(touches.first!.view!.backgroundColor), View tag: " + String(touches.first!.view!.tag))
}

But I expect to get printed out is UIExtendedGrayColorSpace 1 1, View tag: 0, but instead of this I get <UIDynamicSystemColor: 0x600000820b40; name = systemGroupedBackgroundColor>, View tag: 5. This means, that even if I drag my cursor from one view, I still get the first clicked view from touches.first!.view.

How can I get the current selected view?


Solution

  • Answer based on Rob's comment above

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesMoved(touches, with: event)
        if let touch = touches.first {
            if ( !self.grayUIView.frame.contains(touch.location(in: self.grayUIView)) ){
            return
    
            }else {
            //still in current view - process with your logic
    
            }
        }
    }