views:

31

answers:

1

Hello. I'm diving into iOS development and I'm playing with touch events. I have a class named UIPuzzlePiece that's a subclass of UIImageView and it represents the puzzle piece objects that you can move around on the screen. My goal is to be able to move the puzzle pieces around on the screen with my finger.

Currently, I have the touchesBegan and touchesMoved events implemented inside the UIPuzzlePiece class...

// Handles the start of a touch
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
  UITouch *touch = [[event touchesForView:self] anyObject];
  CGPoint cgLocation = [touch locationInView:self];
  [self setCenter:cgLocation];
}

// Handles the continuation of a touch.
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{  
  UITouch *touch = [[event touchesForView:self] anyObject];
  CGPoint cgLocation = [touch locationInView:self];
  [self setCenter:cgLocation];
}

The problem I'm facing is the CGPoint location that is returned represents the location inside the UIPuzzlePiece view, which makes sense, but I need to know the location of the touch inside the parent view. That way the statement [self setCenter:cgLocation] will actually move the UIPuzzlePiece to the location of the touch. I can always write some hacky algorithm to convert it, but I was hoping there's a better or simpler way to accomplish my goal. If I only had a single puzzle piece, I would just implement the touch event code inside the view controller of the parent view, but I have many many puzzle pieces, which is why I'm handling it inside the UIPuzzlePiece view.

Your thoughts? Thanks so much in advance for your wisdom!

+1  A: 

UIView implements -convertRect:fromView:, -convertRect:toView:, -convertPoint:fromView: and -convertPoint:toView:. Sounds like you just need to use one of the latter methods to convert between view coordinate spaces. For example, if you want to convert a CGPoint from the coordinate space of self to the parent view, you can use either [self convertPoint:thePoint toView:self.superview] or you can use [self.superview convertPoint:thePoint fromView:self] (they will do the same thing).

Kevin Ballard
that worked wonderfully, thank you!
BeachRunnerJoe