我试图在touchesbegan方法中使用多个对象(2个UIImageViews)
我使用的是以下代码,但无效。没有错误,但位置只是搞砸了。我该怎么做呢?
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
UITouch *touch = [[event allTouches] anyObject];
if (image1.image == [UIImage imageNamed:@"ball.png"]){
CGPoint location = [touch locationInView:touch.view];
image1.center = location;
}
if (image1.image == [UIImage imageNamed:@"ball2.png"]){
CGPoint location = [touch locationInView:touch.view];
image2.center = location;
}
}
答案 0 :(得分:2)
如果你想在touchesbegen中识别两个图像视图,请试试这个
-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event //here enable the touch
{
// get touch event
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self.view];
if (CGRectContainsPoint(image1.frame, touchLocation))
{
NSLog(@"image1 touched");
//Your logic
}
if (CGRectContainsPoint(image2.frame, touchLocation))
{
NSLog(@"image2 touched");
//your logic
}
}
希望这个帮助
答案 1 :(得分:0)
我想,如果你需要超过image1.image
和if
中心,image2.image
在你的第二个image1
条件中image2
需要image1
。但如果您需要移动图像,则必须执行以下操作 -
例如:如果image2
中心位于(x1,y1)且image1
中心位于(x2,y2)。现在,触摸点(x3,y3)同时属于图像image2
和x4-x3
。如果新拖动位于(x4,y4),则拖动量分别为y4-y3
和x,y
方向- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
UITouch *touch = [[event allTouches] anyObject];
CGPoint location = [touch locationInView:touch.view];
float touchXBeginPoint = [touch locationInView:touch.view].x;
float touchYBeginPoint = [touch locationInView:touch.view].y;
// Now Check touchXBeginPoint, touchYBeginPoint lies in image1, image2
// Calculate the offset distance.
if( /* both are true */ )
{
// Add the offset amount to the image1, image2 center.
}
else if( /* image1 touch is true */ )
{
// Add the offset amount to the image1 center
}
else if( /* image2 touch is true */ )
{
// Add the offset amount to the image2 center
}
}
。将此拖动量添加到图像的中心,以使图像显示在新位置。
伪代码
{{1}}
下载iPhone Game Dev第3章的源代码,了解图片的移动方式。