touchesbegan中的多个对象?

时间:2011-02-10 04:37:07

标签: iphone touches

我试图在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;
    }
}

2 个答案:

答案 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.imageif中心,image2.image在你的第二个image1条件中image2需要image1。但如果您需要移动图像,则必须执行以下操作 -

  1. 检查触摸点是否属于两个对象。
  2. 如果是,则相对移动两个图像(即,将移动的量添加到较早的图像中心)。不将触摸点设为图像中心位置。
  3. 例如:如果image2中心位于(x1,y1)且image1中心位于(x2,y2)。现在,触摸点(x3,y3)同时属于图像image2x4-x3。如果新拖动位于(x4,y4),则拖动量分别为y4-y3x,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章的源代码,了解图片的移动方式。