views:

95

answers:

1

I am working on a website which I would like to work on iPhones, however I want it so they can tap and hold a button and have it continue firing the onclick event. I got it to work in other browsers, but the iPhone is the only one that will need to hold down the button. Is there a way to repeat a function when holding down the button? Thanks.

A: 

Start and stop a timer based on the touchDown and touchUpInside messages sent from the button. Button is assumed to be set-up to link its touchDown and touchUpInside methods to the ones below. You could alternatively set a flag "BOOL firing = TRUE;" on touch down and unset on touch up. Your game loop could look at that flag and make a decision.

@interface TouchTest : UIViewController {
NSTimer *touchDownTimer;
}

@property (nonatomic,retain)  NSTimer   *touchDownTimer;

- (IBAction) touchDown: (id) sender;
- (IBAction) touchUp: (id) sender;

@end

@implementation TouchTest
@synthesize touchDownTimer;

- (void)viewDidLoad {
 [super viewDidLoad];

 UIButton * button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
 button.frame = CGRectMake(100.00, 100.00, 105.0, 37.0);
 [button setTitle:@"Fire at Will" forState:UIControlStateNormal];
 [button addTarget:(id)self action:@selector(touchDown:) forControlEvents:UIControlEventTouchDown];
 [button addTarget:(id)self action:@selector(touchUp:) forControlEvents:UIControlEventTouchUpInside];

 [self.view addSubview:button];
 }

- (IBAction) fireWeapon {
    NSLog(@"WeaponFired");
}

- (IBAction) touchDown :(id) sender{
    touchDownTimer = [NSTimer scheduledTimerWithTimeInterval:(NSTimeInterval).3 target:self selector:@selector(fireWeapon) userInfo:nil repeats:TRUE];
}

- (IBAction) touchUp :(id) sender {
    [touchDownTimer invalidate];
}
@end
Kenny