Search code examples
objective-cuibuttontarget-action

Action on second button click


I want to make a button invisible on the SECOND click. I've got an other action on the first click. How should I do this?

Thanks in advance!


Solution

  • You can either keep state (i.e. count the button clicks) and hide the button on the 2nd click:

    @interface MyClass ()
    {
        NSUInteger _clickCount;
    }
    
    - (IBAction)clicked:(id)sender
    {
       _clickCount++;
       if (_clickCount >= 2) {
            [sender setHidden:YES];
       }
    }
    

    or you could re-assign the action method in the first click:

    - (IBAction)firstClick:(id)sender
    {
        [sender addTarget:self
                   action:@selector(secondClick:)
         forControlEvents:UIControlEventTouchUpInside];
    }
    
    - (IBAction)secondClick:(id)sender
    {
        [sender setHidden:YES];
    }
    

    I like the latter approach better.