检测触摸并按住屏幕iPhone(Xcode)[重复]

Posted

技术标签:

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

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

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

 //code to make him move up

    

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

【问题讨论】:

我认为您需要使用 UILongPressGestureRecognizer 触摸并按住屏幕 你知道我应该怎么写吗? 我的意思是代码 请在下方查看我的回答,了解更多详情***.com/questions/6179347/uibutton-long-press-event 或***.com/questions/34548263/… 【参考方案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 做你的事情。代码更新

以上是关于检测触摸并按住屏幕iPhone(Xcode)[重复]的主要内容,如果未能解决你的问题,请参考以下文章

Xcode Swift - 检测屏幕上颜色的触摸

在 Xcode 中检测任何触摸(不是 TapGesture)

当在 Swift Spritekit 中触摸并按住屏幕时,我将如何向上移动我的节点?

检测用户是不是在 iOS 上触摸过屏幕

Xcode - 如何检测 iPhone 的屏幕尺寸 [关闭]

iphone 恢复出厂设置方法