0

1 つの画像をドラッグ可能にする方法は理解していますが、2 つの異なる画像をドラッグ可能にすることはできないようです。これは私が持っているコードです:

-(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 は私の 2 つの画像です。

上記のコードが機能しない理由がわかりませんか? 誰かが私に与えることができる助けやアドバイスをいただければ幸いです。

前もって感謝します!

4

2 に答える 2

1

if ([[touch view] isEqual:player1])プリミティブ スカラーではなく、オブジェクトを比較するためです。

于 2012-06-07T18:08:30.333 に答える
1

あなたがすべきことは、サブクラス化してそこにUIImageView実装するtouchesMoved:ことです。したがって、ドラッグ可能なビューを初期化すると、両方とも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と、以下の例が表示されます。

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:

お役に立てれば !

UPDATE : -touchesBegan:Dragging a subclass の完全な例が追加されました。これはデフォルトでオフになっているため、プロパティをUIImageView必ずYESに設定してください。.userInteractionEnabled

于 2012-06-07T18:12:57.923 に答える