UIButton Touch and Hold

前端 未结 5 1186
暗喜
暗喜 2020-11-28 07:45

I haven\'t found a very easy way to do this. The ways I\'ve seen require all these timers and stuff. Is there any easy way I can hold a UIButton and cause it to repeat the

5条回答
  •  感情败类
    2020-11-28 08:14

    Unfortunately, it still looks like you have to code this functionality for yourself. simplest way (You still need a timer though):

    A function that performs the action you want to repeat:

    -(void) actionToRepeat:(NSTimer *)timer
    {
        NSLog(@"Action triggered");
    }
    

    in your .h file declare and set a property for a timer:

    @interface ClassFoo
    {
        NSTimer* holdTimer;
    }
    

    Then in the .m make two IBActions:

    -(IBAction) startAction: (id)sender
    {
        holdTimer = [NSTimer scheduledTimerWithTimeInterval:0.4 target:self selector:@selector(actionToRepeat:) userInfo:nil repeats:YES];
        [holdTimer retain];
    }
    
    -(IBAction) stopAction: (id)sender
    {
        [holdTimer invalidate];
        [holdTimer release];
        holdTimer = nil;
    }
    

    Then Just link to the Touch Down event in IB from the button to startAction and the Touch Up Inside to the 'Stop Action'. It isn't a one liner but it allows you to customise the rate the action repeats as well as allowing you to trigger it from another outlet/action.

    You might consider subclassing UIButton and adding this functionality if you are going to be using this functionality often - then it is only (slightly) painful to implement the first time.

提交回复
热议问题