Dragging multiple images in iOS

724 views Asked by At

I'm brand new to touch and drag, and I'm trying to make eight draggable images. Here's what it looks like in my ViewController.m file:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView:self.view];

    //check for which peg is touched

    if ([touch view] == darkGreyPeg){darkGreyPeg.center = location;}
    else if ([touch view] == brownPeg){brownPeg.center = location;}
    //there are six more else ifs
}

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

    [self touchesBegan:touches withEvent:event];

}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    [self ifCollided];

}

If I take out the if statements, and the locationInView:self.view to locationInView:touch.view, I'm able to drag the darkGreyPeg around with no problems, and it triggers my [ifCollided] whenever appropriate.

I'm watching a youTube tutorial (Milmers Xcode tutorials, "Dragging Multiple Images"), and he has exactly this same type of code, and mine doesn't work. Can anyone point me in the direction of why?

Thanks.

3

There are 3 answers

0
Christian Schnorr On

You should not implement these methods in your ViewController, but in your View class that you want to be able to drag around instead.

2
rdelmar On

I think the problem is using == to compare objects:

[touch view] == darkGreyPeg

You should use isEqual: to compare objects:

[[touch view] isEqual:darkGrayPeg]

After Edit: I think the problem is that you forgot to set userInteractionEnabled to YES for the image views. Without doing that, the touch.view will be the superview, not the image view. Also, you probably don't need all those if statements to determine which image view to move, you can just use touch.view:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView:self.view];
    if (![touch.view isEqual:self.view]) touch.view.center = location;
}

If you have other views, besides self.view that you don't want to move, then you either have to exclude them too, or use a different exclusion condition (like only move the object if it's an image view, or only an object with a certain tag value).

0
Lutfi On

Try to check the User interaction Enabled & multiple touch in your view images atribute. Without check the user interaction enabled you can't use multiple dragging. I have try this, and succes to drag multiple image, label or button.