我使用平移手势在拖动线中拖动多个视图,类似于:iOS - Drag and drop collision detection How to detect when your selected item drags over another subview?
我的代码:
- (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;
}
}
}
我有这么多的子视图所以我不想在self.view中循环所有子视图,我只是想在拖动行中检测匹配视图。怎么做?
如果我使用[gestureRecognizer视图],我只会获得第一个视图。
提前感谢您的帮助!
答案 0 :(得分:5)
如果您只想要更简单的代码,可以使用UIView的hitTest:withEvent:
方法在触摸位置查找视图:
- (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;
}
这假设子视图本身没有(交互式)子视图。
答案 1 :(得分:1)
你所拥有的是最好的(即最简单的)方法。除非您注意到性能问题,否则不要担心。
您可以进行一些改进:
break;
)。 答案 2 :(得分:0)
您可以通过使用来实现此目的
CGRectIntersectsRect(<#CGRect rect1#>, <#CGRect rect2#>)