0

我了解如何使单个图像可拖动,但我似乎无法使两个不同的图像可拖动。这是我的代码:

-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

  UITouch *touch = [[event allTouches] anyObject];
  CGPoint location = [touch locationInView:self.view];

  if ([touch view] == player1) {
      player1.center = location;
  } else {
      player2.center = location;
  }

}

player1 和 player2 是我的两个图像。

我不明白为什么上面的代码不起作用?我非常感谢任何人可以给我的任何帮助/建议。

提前致谢!

4

2 回答 2

1

if ([[touch view] isEqual:player1])因为您比较对象,而不是原始标量。

于 2012-06-07T18:08:30.333 回答
1

你应该做的是子类化UIImageViewtouchesMoved:在那里实现。因此,当您初始化可拖动视图时,它们都继承了touchesMoved:功能。你的代码应该看起来更像这样......

//Player.h
@interface Player : UIImageView

CGPoint startLocation;

@end

//Player.m
@implementation Player

- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {   
     // Retrieve the touch point
     CGPoint pt = [[touches anyObject] locationInView:self];
     startLocation = pt;
}

-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

       CGPoint pt = [[touches anyObject] locationInView:self];
       CGFloat dx = pt.x - startLocation.x;
       CGFloat dy = pt.y - startLocation.y;
       CGPoint newCenter = CGPointMake(self.center.x + dx, self.center.y + dy);
       self.center = newCenter;
}

@end

现在,当您初始化Player's 时,示例如下:

Player *player1 = [[Player alloc] initWithImage:[UIImage imageNamed:@"player1.png"]];
[self.view addSubview:player1];
// You can now drag player1 around your view.


Player *player2 = [[Player alloc] init];
[self.view addSubview:player2];
// You can now drag player2 around your view.

假设您将这些添加Players到您UIViewController的视图中。

他们都实施-touchesMoved:

希望这可以帮助 !

更新:添加-touchesBegan:了拖动子类的完整示例UIImageView,确保您将.userInteractionEnabled属性设置为YES ,因为默认情况下这是关闭的。

于 2012-06-07T18:12:57.923 回答