George
George

Reputation: 23

iOS development - Creating multiple draggable images

I understand how to make a single image draggable, but I can't seem to make two different images draggable. This is the code I have:

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

  UITouch *touch = [[event allTouches] anyObject];
  CGPoint location = [touch locationInView:self.view];

  if ([touch view] == player1) {
      player1.center = location;
  } else {
      player2.center = location;
  }

}

player1 and player2 are my two images.

I don't understand why the above code does not work? I'd greatly appreciate any help/advice anyone could give me.

Thanks in advance!

Upvotes: 0

Views: 974

Answers (2)

skram
skram

Reputation: 5314

What you should do is subclass UIImageView and implement touchesMoved: there. So when you Initialize your draggable view they both inherit the touchesMoved: Functionality. Your code should look more like this...

//Player.h
@interface Player : UIImageView

CGPoint startLocation;

@end

//Player.m
@implementation Player

- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {   
     // Retrieve the touch point
     CGPoint pt = [[touches anyObject] locationInView:self];
     startLocation = pt;
}

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

       CGPoint pt = [[touches anyObject] locationInView:self];
       CGFloat dx = pt.x - startLocation.x;
       CGFloat dy = pt.y - startLocation.y;
       CGPoint newCenter = CGPointMake(self.center.x + dx, self.center.y + dy);
       self.center = newCenter;
}

@end

Now when you initialize your Player's, example below:

Player *player1 = [[Player alloc] initWithImage:[UIImage imageNamed:@"player1.png"]];
[self.view addSubview:player1];
// You can now drag player1 around your view.


Player *player2 = [[Player alloc] init];
[self.view addSubview:player2];
// You can now drag player2 around your view.

Assuming you're adding these Players to your UIViewController's view.

They both implement -touchesMoved:

Hope this helps !

UPDATE: Added -touchesBegan: with full example of Dragging a subclass UIImageView, ensure you set the .userInteractionEnabled property to YES as this is OFF by default.

Upvotes: 1

Kyr Dunenkoff
Kyr Dunenkoff

Reputation: 8090

if ([[touch view] isEqual:player1]) because you comparing objects, not primitive scalars.

Upvotes: 1

Related Questions