IOS: Drag more than one image
I try to make more than one image dragable in my iPhone-App. I have followed a tutorial on YouTube but it doesn´t work.
I create the images this way:
image1=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"button_klein.pn开发者_高级运维g"]];
[image1 setFrame:CGRectMake(touchPoint.x-25,touchPoint.y-25,50,50)];
[[self view] addSubview:image1];
image2=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"button2_klein.png"]];
[image2 setFrame:CGRectMake(135,215,50,50)];
[[self view] addSubview:image2];
And then I tried to make them dragable this way:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *myTouch = [[event allTouches] anyObject];
CGPoint location = [myTouch locationInView:self.view];
if ([myTouch view] == image1) {
image1.center = location;
NSLog(@"Test1");
}
if ([myTouch view] == image2) {
image2.center = location;
NSLog(@"Test2");
}
}
But it doesn´t work. When I tried to make one image dragable, it worked.
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *myTouch = [[event allTouches] anyObject];
image1.center = [myTouch locationInView:myTouch.view];
}
Can anybody tell me, where the problem is?
UITouch.view
returns the view that's "handling" the touch (more or less the view returned by -hitTest:withEvent:
. In this case, it is self
, not image1
or image2
. (You can check this by breakpointing -touchesMoved:withEvent: and inspecting the touches yourself.)
You'll want to do something like
if ([image1 pointInside:[myTouch locationInView:image1] withEvent:event]) {
...
} else if ([image2 pointInside: ...]) {
...
}
Note that the touch can be inside both views; I've handled this by choosing image1 by default, but you'll have to decide what's "right".
image1
and image2
are UIImageView
s, you can not compare it against a [(UITouch*) view]
(which is a UIView
). So the comparison never happens, which means the two if
conditions are not overridden.
Try putting image1
and image2
inside 2 UIView
s named image1View
and image2View
, and your code would become if ([myTouch view]==image1View) image1View.center=location
and so on.
精彩评论