Programmatically fire button click event?

后端 未结 5 1207
后悔当初
后悔当初 2020-12-04 07:36

Is there a way to programmatically fire a button click event? I have a button placed there in an UIView, and in a particular scenario i want to click the button via code, no

相关标签:
5条回答
  • 2020-12-04 08:12

    Sort of like Ken's answer, but more flexible as it'll keep track of the buttons actual actions if you change them or add more than one.

    [button sendActionsForControlEvents:UIControlEventTouchUpInside];
    
    0 讨论(0)
  • 2020-12-04 08:22

    If you're talking about a UIButton, you can just call the same method that the UIButton is calling when it is tapped. For example:

    [self myButtonsTargetMethod];
    
    0 讨论(0)
  • 2020-12-04 08:26

    Yes,

    [_button setHighlighted:YES];
    [_button sendActionsForControlEvents:UIControlEventTouchUpInside];
    [_button setHighlighted:NO];
    

    But the problem here is you will not be able to see those event because its too fast . so what you can do is try the above code with NSTimer .

    NSTimer *quick = [NSTimer scheduledTimerWithTimeInterval:2.5 target:self selector:@selector(MeFirst:) userInfo:nil repeats:NO];
    

    MeFirst is the method i have created.

    0 讨论(0)
  • 2020-12-04 08:28

    Why not just execute the code that executes when the user presses the button?

    -(void)myMethod
    {
       // do stuff
    }
    
    -(IBAction)myButtonClick:(id)sender
    {
        [self myMethod];
    }
    
    -(void)clickMyButton
    {
        [self myMethod];
        // OR
        [self myButtonClick:nil];
    }
    
    0 讨论(0)
  • 2020-12-04 08:29

    I had the same issue as above. I would have posted a comment, but my reputation isn't high enough. So, I will instead post the full answer:

    [btn setHighlighted:YES];
    [btn sendActionsForControlEvents:UIControlEventTouchUpInside];
    [btn performSelector:@selector(setHighlighted:) withObject:NO afterDelay:0.25];
    

    This will programmatically hit the button and highlight it for a seemingly normal amount of time. Richie's suggestion didn't work as the button was only highlighted (if at all) for an imperceptible amount of time.

    0 讨论(0)
提交回复
热议问题