2017-06-19 58 views
0

我试图找出如何检测触摸&屏幕上的方法在游戏即时通讯制作。我使用触摸开始单击(使角色向上移动)当他们触摸并持续握住时,我希望角色向前移动。检测屏幕上的触摸和保持IPhone(Xcode)

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

//code to make him move up 

    } 

关于如何检测触摸&的任何想法持有?

+0

我认为你需要使用UILongPressGestureRecognizer进行触摸并按住屏幕 –

+0

你知道我该怎么写吗? –

+0

代码我的意思是 –

回答

0

尝试:

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"); 
} 

}

+0

我试过没有运气,我应该在哪里放置:UILongPressGestureRecognizer * longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress :)]; [self.view addGestureRecognizer:longPress]; –

+0

我把它放在touchesbegan,但它没有工作.. –

+0

UILongPressGestureRecognizer将替代touchesbegan,你应该使用其中一个或另一个 – teixeiras

2

目标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延长你的课程