Cocoa-touch – UIButton Touch and Hold

cocoa-touchuibutton

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 action over and over until it gets released?

Best Answer

You can do the following: Make an NSTimer that will start up when the app starts or in viewDidLoad and also make a boolean.

For example:

//Declare the timer, boolean and the needed IBActions in interface.
@interface className {
NSTimer * timer;
bool g;
}
-(IBAction)theTouchDown(id)sender;
-(IBAction)theTouchUpInside(id)sender;
-(IBAction)theTouchUpOutside(id)sender;

//Give the timer properties.
@property (nonatomic, retain) NSTimer * timer;

Now in your implementation file (.m):

//Synthesize the timer
@synthesize timer;
//When your view loads initialize the timer and boolean.
-(void)viewDidLoad {
    g = false;
    timer = [NSTimer scheduledTimerWithInterval: 1.0 target:self selector:@selector(targetMethod:) userInfo:nil repeats: YES];
}

Now make an IBAction for "Touch Down" set the boolean to lets say true. Then make another IBAction button for "Touch Up Inside" and "Touch Up Outside" assign the boolean to false.

For example:

-(IBAction)theTouchDown {
    g = true;
}

-(IBAction)theTouchUpInside {
    g = false;
}

-(IBAction)theTouchUpOutside {
    g = false;
}

Then in that NSTimer method, put the following:(assume g is the boolean you have declared)

-(void) targetmethod:(id)sender {
    if (g == true) {
        //This is for "Touch and Hold"
    }
    else {
        //This is for the person is off the button.
    }
}

I hope this simplifies everything... I know it still uses a timer but there is not another way.