0

我是全新的触摸和拖动,我试图制作八个可拖动的图像。下面是它看起来像在我ViewController.m文件:在iOS中拖动多个图像

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ 
    UITouch *touch = [[event allTouches] anyObject]; 
    CGPoint location = [touch locationInView:self.view]; 

    //check for which peg is touched 

    if ([touch view] == darkGreyPeg){darkGreyPeg.center = location;} 
    else if ([touch view] == brownPeg){brownPeg.center = location;} 
    //there are six more else ifs 
} 

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ 

    [self touchesBegan:touches withEvent:event]; 

} 

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{ 
    [self ifCollided]; 

} 

如果我拿出if语句,以及locationInView:self.view到locationInView:touch.view,我能够左右拖动darkGreyPeg没有问题,并在适当的时候触发我的[ifCollided]。

我正在看一个youTube教程(Milmers Xcode教程,“拖动多个图像”),他有完全相同类型的代码,而我的工作不起作用。任何人都可以向我指出为什么?

谢谢。

回答

0

你不应该在你的ViewController中实现这些方法,而是在你希望能够拖动的视图类中。

+0

你能解释一下吗?我不是个聪明人。 – novalsi

0

我认为这个问题是用==来比较对象:

[touch view] == darkGreyPeg 

您应该使用isEqual:方法来比较对象:

[[touch view] isEqual:darkGrayPeg] 

编辑后:我认为问题是,您忘记为图像视图设置userInteractionEnabled为YES。如果不这样做,touch.view将是超级视图,而不是图像视图。此外,你可能并不需要所有这些if语句来决定要移动的图像视图,你可以用touch.view:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ 
    UITouch *touch = [[event allTouches] anyObject]; 
    CGPoint location = [touch locationInView:self.view]; 
    if (![touch.view isEqual:self.view]) touch.view.center = location; 
} 

如果您有其他意见,除了self.view,你不想要移动,那么您必须也排除它们,或者使用不同的排除条件(例如,如果它是图像视图或只有具有特定标记值的对象,才移动该对象)。

+0

这不能解决问题。 – novalsi

+0

@novalsi,对不起,这没有帮助,但你应该使用这种方法。通过使用==,你正在比较指针,而不是对象本身。根据你如何得到对象的引用,有时候指针比较起作用,有时不起作用。 – rdelmar

+0

@novalsi,我更新了我的答案,我认为你的问题是。 – rdelmar

1

尝试检查用户交互启用&多次触摸您的视图图像属性。如果没有检查启用的用户交互,您不能使用多个拖动。我尝试了这一点,并成功拖动多个图像,标签或按钮。