LE SANG
LE SANG

Reputation: 11005

How to implement two UIButton at the same time?

I create 2 UIButton(different tag) and connect to 1 Action but when press at the same time, it fires 2 action with small delay.

- (IBAction)keysPress:(UIButton *)sender {
    UIButton *butOne = (UIButton *)[sender viewWithTag:0];
    UIButton *butTwo = (UIButton *)[sender viewWithTag:1];
    NSLog(@"BUT 1: %@ || BUT 2: %@",butOne, butTwo);
}

Log always 2times:

2013-02-19 09:37:40.933 TestActions[1107:c07] BUT 1: <UIButtonLabel: 0xca4d450; frame = (65 67; 9 19); text = 'â'; clipsToBounds = YES; opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0xca4d4c0>> || BUT 2: <UIRoundedRectButton: 0xca4d310; frame = (161 164; 139 153); opaque = NO; autoresize = RM+BM; tag = 1; layer = <CALayer: 0xca4d270>>

2013-02-19 09:37:40.935 TestActions[1107:c07] BUT 1: <UIRoundedRectButton: 0xca4c5c0; frame = (20 164; 135 153); opaque = NO; autoresize = RM+BM; layer = <CALayer: 0xca4c6b0>> || BUT 2: (null)

How to control this case? 2Buttons,1 action - fire 1time.

Upvotes: 1

Views: 154

Answers (2)

ColdLogic
ColdLogic

Reputation: 7265

You do not seem to understand what the sender is. The sender is the button that fired the event, you would program based on what it is.

You need to save a reference to the buttons and then compare them to the sender on entry to the function.

@property (nonatomic, weak) IBOutlet UIButton *butOne;
@property (nonatomic, weak) IBOutlet UIButton *butTwo;

-(IBAction)keysPress:(UIButton *)sender {
   if(sender == [self butOne]) {
       //Do button one actions
   } 

   if(sender == [self butTwo]) {
       //Do button two actions
   }
}

If you don't want to keep references and use the viewWithTag stuff, I REALLY DO NOT SUGGEST IT, but if you do, you can:

- (IBAction)keysPress:(UIButton *)sender {
   UIButton *butOne = (UIButton *)[self viewWithTag:1];
   UIButton *butTwo = (UIButton *)[self viewWithTag:2];
   if(sender == butOne) {
       //Do button one actions
   } 

   if(sender == butTwo) {
       //Do button two actions
   }
}

Upvotes: 5

Guo Luchuan
Guo Luchuan

Reputation: 4731

- (IBAction)keysPress:(UIButton *)sender {
    if(_canClick)
    {
        _canClick = NO;
        UIButton *butOne = (UIButton *)[sender viewWithTag:0];
        UIButton *butTwo = (UIButton *)[sender viewWithTag:1];
        NSLog(@"BUT 1: %@ || BUT 2: %@",butOne, butTwo);
        [self performSelector:@selector(makeButtonCanClick) withObject:nil afterDelay:YOURTIMEINTERVAL];
    }

}

- (void)makeButtonCanClick
{
    _canClick = YES;
}

_canClick is a BOOL ivar , default is YES

Upvotes: 2

Related Questions