你应该做的是子类化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
'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 ,因为默认情况下这是关闭的。