我有UIView,我希望能够拖放子视图,这一切正常一次。
- (void)pan: (UIPanGestureRecognizer *)recognizer
{
if (recognizer.state == UIGestureRecognizerStateBegan) {
CGPoint startPos = [recognizer locationInView:self];
for (UIControl *sv in self.subviews){
if ([sv pointInside:startPos withEvent:nil]){
self.controlBeingDragged = sv;
}
}
}
if (((recognizer.state == UIGestureRecognizerStateChanged) ||
(recognizer.state == UIGestureRecognizerStateEnded)) &&
self.controlBeingDragged){
CGPoint translation = [recognizer translationInView:self];
self.controlBeingDragged.center = CGPointMake(self.controlBeingDragged.center.x + translation.x, self.controlBeingDragged.center.y + translation.y);
[recognizer setTranslation:CGPointZero inView:self];
if (recognizer.state == UIGestureRecognizerStateEnded){
self.controlBeingDragged = nil;
}
}
}
但是,如果我再次尝试拖动相同的UIControl,则包含的视图不再知道它在哪里。我可以通过从原始位置开始再次拖动它,所以很明显我没有做的事情通知包含视图其子视图已移动。但是什么?
答案 0 :(得分:2)
我很惊讶它甚至工作了一次。 pointInside:withEvent:
消息需要接收器的坐标系中的一个点,但是您正在发送一个位于接收者的 superview的坐标系中的点。您可以在每个子视图中使用convertPoint:toView:
将点转换为子视图的坐标系,然后再发送pointInside:withEvent:
消息中的点。
CGPoint subviewPoint = [self convertPoint:startPos toView:sv];
if ([sv pointInside:subviewPoint withEvent:nil]) {
...
您可能还想检查-[UIView hitTest:withEvent:]
消息是否可以替换整个子视图搜索循环。