Objective c 在iOS中拖动多个图像

Objective c 在iOS中拖动多个图像,objective-c,cocoa-touch,uiimageview,touchesbegan,touchesmoved,Objective C,Cocoa Touch,Uiimageview,Touchesbegan,Touchesmoved,我对触摸和拖动是全新的,我正在尝试制作八张可拖动的图像。下面是我的ViewController.m文件中的内容: -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ UITouch *touch = [[event allTouches] anyObject]; CGPoint location = [touch locationInView:self.view]; //check for w

我对触摸和拖动是全新的,我正在尝试制作八张可拖动的图像。下面是我的ViewController.m文件中的内容:

-(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,并在适当的时候触发我的[ifcollide]

我正在看youTube教程(Milmers Xcode教程,“拖动多个图像”),他有完全相同类型的代码,而我的代码不起作用。有人能告诉我为什么吗


谢谢。

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

我认为问题在于使用==来比较对象:

[touch view] == darkGreyPeg
[[touch view] isEqual:darkGrayPeg]
您应该使用isEqual:来比较对象:

[touch view] == darkGreyPeg
[[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之外,您还有其他不想移动的视图,那么您也必须排除它们,或者使用不同的排除条件(例如,如果对象是图像视图,则仅移动对象,或者仅移动具有特定标记值的对象)。

尝试检查用户交互启用和视图图像中的多点触摸。如果未选中已启用的用户交互,则无法使用多个拖动。我已尝试过此方法,并成功拖动了多个图像、标签或按钮。

@novalsi,很抱歉,此方法没有帮助,但您还是应该使用此方法。通过使用==,您是在比较指针,而不是对象本身。根据您获取对象引用的方式,指针比较有时有效,有时无效。@novalsi,我用我认为您的问题所在更新了我的答案。