10

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];
meh-uk
  • 1,919
  • 1
  • 21
  • 36
Ankur
  • 271
  • 1
  • 2
  • 9
  • Not about the question but you have a memory leak here. don't call retain on the button if you don't call release on it later. The retain is not needed as the button is not an ivar and is autoreleased. – Zoleas Dec 01 '11 at 13:17
  • Removed the memory leak. – meh-uk Sep 24 '15 at 10:42
  • [IOS 14 SDK: you can add action with closure callback:](https://stackoverflow.com/questions/5843427/how-do-you-add-an-action-to-a-button-programmatically-in-xcode/640871599#answer-64087159) – Ucdemir Sep 27 '20 at 10:01

6 Answers6

10

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];
Wolverine
  • 4,234
  • 1
  • 24
  • 48
7

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

action:@selector(buttonClick:)
EmptyStack
  • 51,114
  • 22
  • 146
  • 177
2

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{

}
Vvk
  • 3,966
  • 28
  • 49
1

Swift code:

button.addTarget(self, action:"action_button", forControlEvents:.TouchUpInside)
...
func action_button() {
    //  implement me
}
superarts.org
  • 6,795
  • 1
  • 55
  • 43
1
action:@selector(buttonClick:)
Srikar Appalaraju
  • 69,116
  • 53
  • 210
  • 260
Gaurav Govilkar
  • 154
  • 1
  • 1
  • 10
0
  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)
ScottyBlades
  • 9,795
  • 4
  • 62
  • 71