Wayne Filkins
Wayne Filkins

Reputation: 524

How to drag finger across 2 views and know which view it is on at all times

Okay so what I'm trying to figure out is how to allow the user to touch a view, drag their finger across the view to another view, and always know which view they are dragging across. So if they go back and forth you can constantly print which view they are currently dragging their finger on. The hard part about this is that the views are in two separate table view cells. I originally didn't mention that because I didn't think it would make a difference, but everything I try isn't working because of them being in table cells.

Upvotes: 0

Views: 164

Answers (2)

Ravi
Ravi

Reputation: 2451

You can do this by using UIControl class, make your views as subclass of UIControl

Now add action for your views with control event TouchDragInside ( UIControlEvents.TouchDragInside). Then whenever you drag inside the view this action method will be called.

You can also know when dragging exited by using control event UIControlEvents.TouchDragExit

FYI

Edit: To detect the touch, when we start drag from one we to another view we can use action with UIControlEvents.TouchDragOutside control event.Use combination of TouchDragInside and TouchDragOutside control events for the two views to detect the touch when we dragged from one view to another view.

Upvotes: 1

Basheer_CAD
Basheer_CAD

Reputation: 4919

While the user keeps dragging you can use touchMoved in the parent view or the viewController, then you can use the method hitTest:inPoint which will return the view that is under the point.

Here is an example from a viewController:

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {

    // first get the location in the parent view
    let location = touches.first!.locationInView(self.view)

    // ask the parent view to give you the subview falling under the location 
    let view = self.view.hitTest(location, withEvent: event)

    // do what you want with it
    print("View: %@", NSStringFromClass((view?.classForCoder)!))
}

NOTE: All your subviews must have userInteractionEnabled = true

Upvotes: 1

Related Questions