我理解如何使单个图像可拖动,但我似乎无法使两个不同的图像可拖动。这是我的代码:
-(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是我的两张图片。
我不明白为什么上面的代码不起作用?我非常感谢任何人可以给我的任何帮助/建议。
提前致谢!
答案 0 :(得分:1)
if ([[touch view] isEqual:player1])
因为你比较的是对象,而不是原始的标量。
答案 1 :(得分: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:
希望这有帮助!
更新:添加了-touchesBegan:
,其中包含拖动子类UIImageView
的完整示例,请确保将.userInteractionEnabled
属性设置为是因为默认情况下 OFF 。