Adding an action to a UIButton via code programmatically

suggest change

To add a method to a button, first create an action method:

Objective-C

-(void)someButtonAction:(id)sender {
  // sender is the object that was tapped; in this case it's the button.
    NSLog(@"Button is tapped"); 
}

Swift

func someButtonAction() {
    print("Button is tapped")
}

Now to add this action method to your button, you have to write following line of code:

Objective-C

[yourButtonInstance addTarget:self action:@selector(someButtonAction:) forControlEvents:UIControlEventTouchUpInside];

Swift

yourButtonInstance.addTarget(self, action: #selector(someButtonAction), forControlEvents: .TouchUpInside)

For the control-events parameter, any member of the UIControlEvents enum is valid.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents