【问题标题】:Detecting Touch and hold on screen IPhone (Xcode) [duplicate]检测触摸并按住屏幕iPhone(Xcode)[重复]
【发布时间】:2017-06-19 11:22:11
【问题描述】:

我正在尝试找出如何在我制作的游戏中检测触摸并按住屏幕的方法。我使用触摸开始进行单击(使角色向上移动)当他们触摸并保持按住时,我希望角色直接向前移动。

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

 //code to make him move up

    }

关于如何检测触摸和按住的任何想法?

【问题讨论】:

标签: ios objective-c iphone xcode sprite-kit


【解决方案1】:

Objective-c

// Add guesture recognizer
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(buttonDidLongPress:)];
    [self.button addGestureRecognizer:longPress];

// Call back event
- (void)buttonDidLongPress:(UILongPressGestureRecognizer*)gesture
{
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan:
        {
            // Code
        }
            break;
        case UIGestureRecognizerStateEnded:
        {
            //Code
        }
            break;
        default:
            break;
    }
}

斯威夫特

// Add guesture recognizer
        let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPress(_:)))
        self.button.addGestureRecognizer(longPress)

// Call back event
func longPress(guesture: UILongPressGestureRecognizer) {

        switch guesture.state {
        case UIGestureRecognizerState.began:
            //Code
            break

        case UIGestureRecognizerState.ended:
            //Code
            break

        default:
            break
        }
    }

别忘了用 UIGestureRecognizerDelegate 扩展你的类

【讨论】:

    【解决方案2】:

    试试:

    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
    [self.view addGestureRecognizer:longPress];
    
    -(void) handleLongPress: (UIGestureRecognizer *)longPress {
    switch (longPress.state) {
        case UIGestureRecognizerStateBegan:
            // Called when long press for minimum time duration
            break;
        case UIGestureRecognizerStateChanged:
            // Long pressed and dragged 
            break;
        case UIGestureRecognizerStateRecognized:
            // Successfully recognised Long touch
            break;
    
        default:
            break;
    }
    if (longPress.state==UIGestureRecognizerStateEnded) {
        NSLog(@"LONG PRESSED");
    }
    

    }

    【讨论】:

    • 我试过没有运气,我应该在哪里放置:UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; [self.view addGestureRecognizer:longPress];
    • 我把它放在 touchesbegan 中,但没有用..
    • UILongPressGestureRecognizer 将替代 touchesbegan,你应该使用其中一个
    • 在UIGestureRecognizerStateEnd 做你的事情。代码更新
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-08
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-14
    • 2011-12-16
    相关资源
    最近更新 更多