LE SANG LE SANG - 4 months ago 26
iOS Question

Is there another way to detect views when dragging other View over it?

I use pan gesture to drag multi-views in dragging line,something like that: iOS - Drag and drop collision detection How to detect when your selected item drags over another subview?

My code:

- (void)viewDidLoad
{
[super viewDidLoad];
for (UIView *aView in self.view.subviews) {
[self addGestureRecognizersToPiece:aView];
}
}

- (void)addGestureRecognizersToPiece:(UIView *)piece
{
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panPiece:)];
[piece addGestureRecognizer:panGesture];
}



- (void)panPiece:(UIPanGestureRecognizer *)gestureRecognizer
{
CGPoint dragingPoint = [gestureRecognizer locationInView:self.view];

for (UIView *aView in self.view.subviews) {
if (CGRectContainsPoint([aView frame], dragingPoint)) {
aView.center = dragingPoint;
}
}

}


I have so many subviews so I don't want to loop all subviews in self.view, I just want to detect match views in dragging line. How to do that?

If I use [gestureRecognizer view], I just get the first View.

Thanks for help in advance!

Answer

If you just want simpler code you can use UIView's hitTest:withEvent: method to find the view at the touch location:

- (void)panPiece:(UIPanGestureRecognizer *)gestureRecognizer
{
    CGPoint draggingPoint = [gestureRecognizer locationInView:self.view];
    UIView *hitView = [self.view hitTest:draggingPoint withEvent:nil];
    if (hitView.superview == self.view)
        hitView.center = draggingPoint;
}

This assumes the subviews do not have (interactive) subviews themselves.