Reputation: 25
I am trying to build an app where two buttons need to be pressed simultaneously.
if (self->button1.touchInside && self->button2.touchInside) {
NSLog(@"Two buttons pressed");
}
else if (!self->button1.touchInside | !self->button2.touchInside){
NSLog(@"One button pressed");
}
Both buttons are attached to the View Controller using the 'Touch Down' gesture option. When I press both buttons at the same time (with one press) the console window prints:
One button pressed
Two buttons pressed
This interferes with how my application works. I only want the console to print
Two buttons pressed
Thanks
Upvotes: 0
Views: 327
Reputation: 51
What i understand is you need to take some action when both the buttons are pressed. Watever you try, there is going to be a lag between the touches of these buttons. A better approach would be to check if press on both buttons is finished. Hope following works for you -
@property(nonatomic, assign) BOOL firstButtonPressed;
@property(nonatomic, assign) BOOL secondButtonPressed;
//in init or viewDidLoad or any view delegates
_firstButtonPressed = NO;
_secondButtonPressed = NO;
//Connect following IBActions to Touch Down events of both buttons
- (IBAction)firstButtonPressed:(UIButton *)sender {
_firstButtonPressed = YES;
[self checkForButtonPress];
}
- (IBAction)secondButtonPressed:(UIButton *)sender {
_ secondButtonPressed = YES;
[self checkForButtonPress];
}
- (void)checkForButtonPress {
if (_firstButtonPressed && _secondButtonPressed) {
NSlog(@"Two buttons pressed");
}
}
Upvotes: 1
Reputation: 40030
You can do it using two boolean flags like this:
@property(nonatomic, assign) BOOL firstButtonPressed;
@property(nonatomic, assign) BOOL secondButtonPressed;
- (void)firstButtonTouchDown:(id)sender
{
_firstButtonPressed = YES;
if (_secondButtonPressed)
{
// Both buttons pressed.
}
}
- (void)secondButtonTouchDown:(id)sender
{
_secondButtonPressed = YES;
if (_firstButtonPressed)
{
// Both buttons pressed.
}
}
- (void)firstButtonTouchCancelled:(id)sender
{
_firstButtonPressed = NO;
}
- (void)secondButtonTouchCancelled:(id)sender
{
_secondButtonPressed = NO;
}
Alternatively, you can also start a timer when a touch is down and check if the second touch happens during time interval you specify.
Upvotes: 0