【问题标题】:Dragging multiple images in iOS在 iOS 中拖动多个图像
【发布时间】:2013-12-15 21:14:25
【问题描述】:

我是触摸和拖动的新手,我正在尝试制作八个可拖动的图像。这是我的 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,它会在适当的时候触发我的 [ifCollided]。

我正在看一个 YouTube 教程(Milmers Xcode 教程,“拖动多个图像”),他有完全相同类型的代码,而我的代码不起作用。谁能指出我为什么?

谢谢。

【问题讨论】:

    标签: objective-c cocoa-touch uiimageview touchesbegan touchesmoved


    【解决方案1】:

    尝试在您的视图图像属性中检查用户交互已启用和多点触控。如果不检查启用的用户交互,您将无法使用多次拖动。我已经尝试过了,并且成功拖动了多个图像、标签或按钮。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

        • @novalsi,对不起,这没有帮助,但无论如何你都应该使用这种方法。通过使用 ==,您是在比较指针,而不是对象本身。根据您获取对象引用的方式,有时指针比较有效,有时无效。
        • @novalsi,我用我认为你的问题更新了我的答案。
        猜你喜欢
        • 2019-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-18
        • 1970-01-01
        • 2014-03-18
        • 1970-01-01
        • 2023-04-01
        相关资源
        最近更新 更多