'How to add action for UIButton

I am new to iPhone technology. Please anyone tell me how to add action for UIButton.

UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(0, 0, 100, 25);
btn.backgroundColor = [UIColor clearColor];
[btn setTitle:@"Play" forState:UIControlStateNormal];
[btn addTarget:self action:(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
btn.center = self.center;
[self addSubview:btn];


Solution 1:[1]

Use This

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button addTarget:self 
       action:@selector(aMethod:)forControlEvents:UIControlEventTouchDown];
    [button setTitle:@"Show View" forState:UIControlStateNormal];
    button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
    [view addSubview:button];

Solution 2:[2]

You specify selectors using @selector(). So, the action parameter looks like,

action:@selector(buttonClick:)

Solution 3:[3]

Use Like This

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        btn.frame = CGRectMake(0, 0, 100, 25);
        btn.backgroundColor = [UIColor clearColor];
        [btn setTitle:@"Play" forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(btnTapped:) forControlEvents:UIControlEventTouchUpInside];
        btn.center = self.center;
[self addSubview:btn];

and add your selector method

-(IBAction)btnTapped:(id)sender{

}

Solution 4:[4]

action:@selector(buttonClick:)

Solution 5:[5]

Swift code:

button.addTarget(self, action:"action_button", forControlEvents:.TouchUpInside)
...
func action_button() {
    //  implement me
}

Solution 6:[6]

  1. Create a function with @objc
  2. add the function as a target to the UIButton. like so:
menuButton.addTarget(self, action: #selector(menuTapped), for: .touchUpInside)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wolverine
Solution 2 EmptyStack
Solution 3 Vvk
Solution 4 Srikar Appalaraju
Solution 5 superarts.org
Solution 6 ScottyBlades