开发者

How can I convert the coordinates of a touch event on a subview to the coordinates in its parent view?

开发者 https://www.devze.com 2023-01-23 07:48 出处:网络
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 ar

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 handlin开发者_Python百科g it inside the UIPuzzlePiece view.

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


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消