在手指下拖动UIView

Par*_*x13 9 iphone itunes move uiview drag

我想点击UIView并拖动并按照我的手指操作,简单就够了.但最简单的方法是将对象中心设置为点击发生的位置(这不是我想要的),我希望它移动,就好像你抓住了对象的任何地方一样.

这是一个非常有用的方法,它是在一个iTunes U视频中引用的.该脚本没有使用deltaX,deltaY来拖动你点击它下面的图像,而不是让它在你的手指下方居中,但我不记得那个代码是什么!

有没有人引用这段代码?或者也许有一种有效的方法在没有uiview.center = tap.center概念的情况下在手指下移动UIViews?

小智 11

以下代码是允许面板/视图移动的简单手势识别器的示例.您不是修改中心,而是修改原点[基本上通过为目标视图设置新框架].

您可以在您的情况下对其进行优化,这样您就不必深入了解gesture.view等

-(void)dragging:(UIPanGestureRecognizer *)gesture
{
    if(gesture.state == UIGestureRecognizerStateBegan)
    {
        //NSLog(@"Received a pan gesture");
        self.panCoord = [gesture locationInView:gesture.view];


    }
    CGPoint newCoord = [gesture locationInView:gesture.view];
    float dX = newCoord.x-panCoord.x;
    float dY = newCoord.y-panCoord.y;

gesture.view.frame = CGRectMake(gesture.view.frame.origin.x+dX, gesture.view.frame.origin.y+dY, gesture.view.frame.size.width, gesture.view.frame.size.height);
 }
Run Code Online (Sandbox Code Playgroud)

斯威夫特4:

@objc func handleTap(_ sender: UIPanGestureRecognizer) {
        if(sender.state == .began) {
            self.panCoord = sender.location(in: sender.view)
        }

        let newCoord: CGPoint = sender.location(in: sender.view)

        let dX = newCoord.x - panCoord.x
        let dY = newCoord.y - panCoord.y

        sender.view?.frame = CGRect(x: (sender.view?.frame.origin.x)!+dX, y: (sender.view?.frame.origin.y)!+dY, width: (sender.view?.frame.size.width)!, height: (sender.view?.frame.size.height)!)
    }
Run Code Online (Sandbox Code Playgroud)

  • 您的代码中的"panCoord"是什么? (2认同)

ton*_*ack 7

以下是来自Apple的MoveMe项目的代码,关键是在touchesMoved方法中执行此操作.它允许UIView(PlacardView)在用户触摸的任何地方看到触摸和移动.希望这可以帮助.

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

UITouch *touch = [touches anyObject];

// If the touch was in the placardView, move the placardView to its location
if ([touch view] == placardView) {
    CGPoint location = [touch locationInView:self];
    placardView.center = location;
    return;
   }
}
Run Code Online (Sandbox Code Playgroud)

  • 问题是如果你移动手指事件而不在视图中开始,它将改变它的位置,这会导致跳跃. (4认同)

Tig*_*ing 0

我认为您正在谈论跟踪者应用程序...

// Tell the "stalker" rectangle to move to each touch-down
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [UIView beginAnimations:@"stalk" context:nil];
    [UIView setAnimationDuration:1];
    //[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationBeginsFromCurrentState:YES];

    // touches is an NSSet.  Take any single UITouch from the set
    UITouch *touch = [touches anyObject];

    // Move the rectangle to the location of the touch
    stalker.center = [touch locationInView:self];
    [UIView commitAnimations];
}
Run Code Online (Sandbox Code Playgroud)