Way to make a UIButton continuously fire during a press-and-hold situation?

后端 未结 4 1246
伪装坚强ぢ
伪装坚强ぢ 2020-11-29 19:21

You know how Mario just keeps running to the right when you press and hold the right-button on the D-Pad? In the same manner, I want my UIButton to continuously fire its act

4条回答
  •  清歌不尽
    2020-11-29 20:20

    Don't use a button, use multi-touch and NSTimer:

    Make a view-local NSTimer object inside your interface, then use it to start/cancel the timer

    -(void)movePlayer:(id)sender {
       
    }
    
    -(void)touchesBegan:(NSSet*)touches  withEvent:(UIEvent*)event {
        timer = [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(movePlayer:) userInfo:nil repeats:YES];
    }
    
    -(void)touchesEnded:(NSSet*)touches  withEvent:(UIEvent*)event {
       if (timer != nil) 
          [timer invalidate];
          timer = nil;
    }
    
    -(void)touchesMoved:(NSSet*)touches  withEvent:(UIEvent*)event {
        if (timer != nil) {
           [timer invalidate];
           timer = nil;
        }
    }
    

    This way, you can repeat the event at a predefined interval, and not have to rely on a button, and get the repeat behaviour you're looking for. Note the touchesMoved trigger - if they move their finger, this cancels the timer, and the player stops moving.

提交回复
热议问题