Stive
Stive

Reputation: 6888

How to trigger UIButton action programmatically

I have several buttons in one class and their actions are separate. I created the instance of that class in another class, and I have the UIButton array in the 2nd class. I want to call each button's action programmatically. Is there any way to do this in iOS?

Upvotes: 15

Views: 13601

Answers (3)

Tal Zion
Tal Zion

Reputation: 6526

For Swift 3.0/4.0/5.0:

button.sendActions(for: .touchUpInside)

Upvotes: 21

Thomas Keuleers
Thomas Keuleers

Reputation: 6115

UIButton has a method to invoke the targets/selectors that are linked to a certain control event:

[button sendActionsForControlEvents:UIControlEventTouchUpInside];

2022 Swift syntax:

someButton.sendActions(for: .primaryActionTriggered)

Upvotes: 37

mezbah
mezbah

Reputation: 36

You can simply call first class's action method as instance method from other classes by passing a UIbutton id

e.g.: in first class "ClassA"

- (IBAction)classAbuttonAction1:(id)sender;
- (IBAction)classAbuttonAction2:(id)sender;

from another class

UIButton *bClassButton = [[UIButton alloc]init];    
ClassA *instance = [[ClassA alloc]init];

[instance classAbuttonAction1:bClassButton];
[instance classAbuttonAction2:bClassButton];

Upvotes: 0

Related Questions