iOS UIButton Adding an action to an UIButton via Code (programmatically)


Example

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 its 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 ControlEvents parameter, all members of ENUM UIControlEvents are valid.