Iphone IOS:拖动多个图像
我尝试在iPhone应用程序中绘制多幅图像。我在YouTube上观看了一个教程,但它不起作用 我以这种方式创建图像:Iphone IOS:拖动多个图像,iphone,cocoa-touch,xcode,Iphone,Cocoa Touch,Xcode,我尝试在iPhone应用程序中绘制多幅图像。我在YouTube上观看了一个教程,但它不起作用 我以这种方式创建图像: image1=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"button_klein.png"]]; [image1 setFrame:CGRectMake(touchPoint.x-25,touchPoint.y-25,50,50)]; [[self view] addSubview:image1]; im
image1=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"button_klein.png"]];
[image1 setFrame:CGRectMake(touchPoint.x-25,touchPoint.y-25,50,50)];
[[self view] addSubview:image1];
image2=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"button2_klein.png"]];
[image2 setFrame:CGRectMake(135,215,50,50)];
[[self view] addSubview:image2];
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *myTouch = [[event allTouches] anyObject];
CGPoint location = [myTouch locationInView:self.view];
if ([myTouch view] == image1) {
image1.center = location;
NSLog(@"Test1");
}
if ([myTouch view] == image2) {
image2.center = location;
NSLog(@"Test2");
}
}
然后我试着用这种方式让它们可以拖动:
image1=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"button_klein.png"]];
[image1 setFrame:CGRectMake(touchPoint.x-25,touchPoint.y-25,50,50)];
[[self view] addSubview:image1];
image2=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"button2_klein.png"]];
[image2 setFrame:CGRectMake(135,215,50,50)];
[[self view] addSubview:image2];
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *myTouch = [[event allTouches] anyObject];
CGPoint location = [myTouch locationInView:self.view];
if ([myTouch view] == image1) {
image1.center = location;
NSLog(@"Test1");
}
if ([myTouch view] == image2) {
image2.center = location;
NSLog(@"Test2");
}
}
但它不起作用。当我试图使一个图像可拖动时,它成功了
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *myTouch = [[event allTouches] anyObject];
image1.center = [myTouch locationInView:myTouch.view];
}
有人能告诉我问题出在哪里吗?
image1
和image2
是UIImageView
s,您无法将其与[(UITouch*)视图]
(这是UIView
)进行比较。因此,比较永远不会发生,这意味着这两个条件不会被覆盖
尝试将image1
和image2
放入名为image1View
和image2View
,如果([myTouch view]==image1View)image1View.center=location
等等,代码将变成。UITouch.view
返回“处理”触摸的视图(或多或少是由-hitTest:withEvent:
返回的视图。在这种情况下,它是self
,而不是image1
或image2
(您可以通过中断-touchesMoved:withEvent:并亲自检查触摸来检查。)
你会想做类似的事情
if ([image1 pointInside:[myTouch locationInView:image1] withEvent:event]) {
...
} else if ([image2 pointInside: ...]) {
...
}
请注意,触摸可以在两个视图中进行;我通过默认选择image1来处理这个问题,但您必须决定什么是“正确的”。当然可以。UIImageView子类UIView,当然,您可以将任何指针与任何其他指针进行比较。“比较从未发生”从未发生。