【问题标题】:Draggable UIView moves incorrectly可拖动的 UIView 移动不正确
【发布时间】:2013-12-02 02:00:33
【问题描述】:

我正在使用 UIView 子类在 AVPlayer 中播放视频。它工作正常,没有问题。但是,我希望这个视图是可拖动的。在它的类中,我有 touchesMoved 委托方法,它执行以下操作:

CGPoint tap = [[touches anyObject] locationInView:self];
self.center = tap;

但是,这是令人难以置信的故障。边界为{{0, 0}, {342, 256}} 的uiview 非常迅速地从我的手指所在的位置移动到屏幕的左上角,当我松开时,它消失了。如何使我在 UIView 中点击的点移动到我的手指当前所在的位置,为什么它会移动到左上角?我是不是做错了什么??

【问题讨论】:

  • 为什么不直接使用 UIPanGestureRecognizer?
  • @0x7fffffff:因为我对 UIPanGestureRecognizer 没有任何经验。使用它而不是 touchesMoved 的优点是什么?

标签: ios objective-c cocoa-touch drawrect touchesmoved


【解决方案1】:

您的参考框架有问题。当您请求locationInView:self 时,您是在请求子视图坐标系中的触摸。 (即视图的左上角是 (0, 0)。)不过,子视图的 center 属性位于父视图的坐标系中(即父视图的左上角是 (0, 0) ))。因此,如果您点击子视图的左上角,您返回的 locationInView:self 将是 (0, 0) 并将其设置为子视图的中心会将其定位在超级视图的左上角 查看

您可能想要获得locationInView:self.superview,以便您返回的点位于超级视图的坐标系中。或者,更好的是,让超级视图进行触摸处理。 (修改自己的中心通常被认为是一种糟糕的形式;每个视图通常被设计成不知道其父视图及其在其中的位置。)

【讨论】:

    【解决方案2】:

    你应该尝试做这样的事情:

    记住touchesBegan中的起始位置:

    UITouch *touch = [touches anyObject];
    self.startTouchPoint = [touch locationInView:self];         
    

    通过 touchesMoved 中的位置差异移动视图:

        CGPoint movedPoint = [touch locationInView:self];
    
        CGFloat deltaX = movedPoint.x - _startTouchPoint.x;
        CGFloat deltaY = movedPoint.y - _startTouchPoint.y;
        CGPoint center = self.center;
        center.x += x;
        center.y += y;
        self.center = center;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-27
      • 1970-01-01
      • 2017-09-28
      • 2014-05-10
      • 1970-01-01
      • 2012-05-09
      相关资源
      最近更新 更多