【问题标题】:ios drag and drop subview only working onceios拖放子视图只工作一次
【发布时间】:2012-07-11 22:01:42
【问题描述】:

我有 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,则包含视图不再​​知道它在哪里。我可以从原始位置开始再次拖动它,所以很明显,我没有做一些事情来通知包含视图它的子视图已经移动。但是什么?

【问题讨论】:

  • 当您再次尝试拖动同一个控件时,上述代码的哪一部分没有运行;如果您使用跟踪写入或调试器,哪些行没有到达?

标签: objective-c ios uiview drag-and-drop


【解决方案1】:

我很惊讶它甚至可以工作一次。 pointInside:withEvent: 消息需要 receiver 的 坐标系中的一个点,但您发送的点是接收者 superview 的 坐标系中的一个点。您可以为每个子视图使用convertPoint:toView: 将点转换为子视图的坐标系,然后再在pointInside:withEvent: 消息中发送点。

CGPoint subviewPoint = [self convertPoint:startPos toView:sv];
if ([sv pointInside:subviewPoint withEvent:nil]) {
    ...

您可能还想检查-[UIView hitTest:withEvent:] 消息是否可以替换整个子视图搜索循环。

【讨论】:

  • 谢谢罗伯。选项 1 奏效。现在没有时间尝试选项 2,但稍后会这样做。
  • 好的,选项 2 的试用时间比我想象的要少,而且效果也很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-17
  • 1970-01-01
  • 1970-01-01
  • 2012-03-31
  • 1970-01-01
  • 2019-09-16
相关资源
最近更新 更多