2017-06-19 98 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延長你的課程