Attaching a Method to a Button

suggest change

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

Objective-C

-(void) someButtonAction{
    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), for: .touchUpInside)

The action method must be exposed to Objective-C (@objc) for #selector to find it. Any UIControl.Event value is valid.

Feedback about page:

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



Table Of Contents