Question

hey guys i was wondering if there was away to make an object like a UIImageView draggable. I am aware of the UITouch and touches i.e.

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *drag=[[event allTouches] anyObject];
    player.center=[drag locationInView:self.view];
}

but in this way it is possible for the user to make the object jump across the screen to where he or she touches the screen but i want the user to have to manually drag the object across the screen.

please explain with code and let me know if i have to be more specific or clear...

Was it helpful?

Solution

You can do this:

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

    UITouch *aTouch = [touches anyObject];
    CGPoint location = [aTouch locationInView:self.view];

    if(CGRectContainsPoint(self.playerView.frame,location)) {
        [UIView beginAnimations:@"Dragging A DraggableView" context:nil];
        self.playerView.center = location;
        [UIView commitAnimations];
    }

}

This should give you a smooth animation.

OTHER TIPS

if you want your user to drag&drop, first you have to check if the touch is inside the imageview rect frame. To improve the user experience, you can detect the touch offset from the imageview center; a good place to do this is inside the touchesBegan:withEvent:. After that, you have to change the position of the imageview, like this:

CGPoint touchOffset; //insert this inside your interface private iVars
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
     UITouch *drag=[[event allTouches] anyObject];
     CGPoint touchLocation = [drag locationInView:self.view];
     touchOffset = CGPointMake(player.center.x-touchLocation.x,player.center.y-touchLocation.y)
     if(CGRectContainsPoint(player.frame,touchLocation)
         player.center = CGPointMake(touchLocation.x+touchOffset.x,touchLocation.y+touchOffset.y);
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *drag=[[event allTouches] anyObject];
    CGPoint touchLocation = [drag locationInView:self.view];
    if(CGRectContainsPoint(player.frame,touchLocation)
        player.center = CGPointMake(touchLocation.x+touchOffset.x,touchLocation.y+touchOffset.y);
}

P.S. - Next time try to search similar questions...

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

    UITouch* aTouch = [touches anyObject];
    UIView* aView = [aTouch view];
    if (aView != self.view) {
        [self.view bringSubviewToFront:aView];
    }
}

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

    UITouch* aTouch = [touches anyObject];
    UIView* aView = [aTouch view];
    if (aView != self.view) {
        aView.center = [aTouch locationInView:self.view];

    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top