Dragging UIView under finger [duplicate]

隐身守侯 提交于 2019-11-30 09:10:40
binary_falcon

The following code is an example of a simple gesture recognizer that will allow panel / view movement. Instead of modifying the center, you're modifying the origin point [basically by setting a new frame for the target view].

You can optimize this in your situation so you're not having to drill down into the gesture.view... etc

-(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);
 }

Swift 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)!)
    }
tony.stack

Here is the code from Apple's MoveMe project the key is to do this in the touchesMoved method. It allows the UIView(PlacardView) to see the touch and move wherever the user's touch goes. Hope this helps.

- (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;
   }
}

I think you are talking about the stalker app...

// 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];
}

You can save both the point where you touched (T) and the current position of the view (O). In touchMoved, you can move it based on the new point by adding (O-T).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!