Search code examples
objective-cxcodecocoa-touchibaction

Fire IBAction automatically


I have a button and want to fire it automatically by itself without touch. Is it possible?

-(IBAction)xxx:(id)sender 

Solution

  • My answer assumes you have the method:

    - (IBAction)someAction:(UIButton *)sender {
    }
    

    and that you have a reference to the button in an instance variable named someButton.

    If you just need to "fire it" now, simply call it:

    [self someAction:someButton];
    

    If you need to "fire it" once, but later, you can do:

    // call it 5 seconds from now
    [self performSelector:@selector(someAction:) withObject:someButton afterDelay:5.0];
    

    If you want to fire it repeatedly, use a timer:

    myTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(buttonTimerFired) userInfo:nil repeats:YES];
    
    - (void)buttonTimerFired {
        [self someAction:someButton];
    }