我尝试在我的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];
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];
}谁能告诉我,问题出在哪里?
发布于 2011-06-20 09:39:57
UITouch.view返回“处理”触摸的视图(或多或少由-hitTest:withEvent:返回的视图。在本例中,它是self,而不是image1或image2。(您可以通过断点-touchesMoved:withEvent:并自己检查触摸来检查这一点。)
你会想做一些类似这样的事情
if ([image1 pointInside:[myTouch locationInView:image1] withEvent:event]) {
...
} else if ([image2 pointInside: ...]) {
...
}请注意,触摸可以在两个视图中进行;我默认选择了image1来处理这个问题,但您必须决定什么是“正确的”。
发布于 2011-06-20 05:25:26
image1和image2是UIImageViews,您不能将其与[(UITouch*) view] (即UIView)进行比较。因此,比较永远不会发生,这意味着两个if条件不会被覆盖。
尝试将image1和image2放入名为image1View和image2View的2个UIView中,您的代码将变为if ([myTouch view]==image1View) image1View.center=location,依此类推。
https://stackoverflow.com/questions/5107048
复制相似问题