Lets say I wan\'t to add 1 to an integer. This will only be done when I push down on a UIButton
and then release my finger on another UIButton
.
Try implementing the button you wish to touch down on as a "Touch Down", "Touch Up Inside", and "Touch Up Outside" button.
UIButtons can respond to many differing types of events Touch Cancel Touch Down Touch Down Repeat Touch Drag Enter Touch Drag Exit Touch Drag Inside Touch Drag Outside Touch Up Inside Touch Up Outside
You can implement different action code for each of these for each button for best control of whatever you wish. The simplistic case only uses the 2 I mentioned above.
THIS CODE HAS BEEN TESTED AND DOES WORK
In your ViewController header file (here was mine):
@interface ViewController : UIViewController{
IBOutlet UIButton * upButton; // count up when finger released button
IBOutlet UIButton * downButton;
IBOutlet UILable * score;
BOOL isButtonDown;
unsigned int youCounter;
}
-(IBAction)downButtonDown:(id)sender;
-(IBAction)downButtonUpInside:(id)sender;
-(IBAction)downButtonDragOutside:(id)sender event:(UIEvent *)event;
-(IBAction)downButtonUpOutside:(id)sender event:(UIEvent *)event;
@end
In your .xib, connect the down button (the one you wish to be your original finger pressed button) to the proper actions above.
In your ViewController.m file
-(void)viewDidLoad{
[super viewDidLoad];
isButtonDown = NO;
youCounter = 0;
}
-(IBAction)downButtonDown:(id)sender{
isButtonDown = YES;
}
-(IBAction)downButtonUpInside:(id)sender{
isButtonDown = NO;
}
-(IBAction)downButtonDragOutside:(id)sender event:(UIEvent *)event{
NSArray theTouches = [[event allTouches] allObjects];
[downButton setHighlighted:YES];
if(YES == [upButton pointInside:[[theTouches objectAtIndex:0] locationInView:upButton] withEvent:event]){
[upButton setHighlighted:YES];
}else{
[upButton setHighlighted:NO];
}
}
-(IBAction)downButtonUpOutside:(id)sender event:(UIEvent *)event{
if(YES == [upButton pointInside:[[theTouches objectAtIndex:0] locationInView:upButton] withEvent:event]){
youCounter++;
score.text = [NSString stringWithFormat:@"Score = %d", youCounter];
}
[downButton setHighlighted:NO];
[upButton setHighlighted:NO];
}