Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];
like image 495
Ankur Avatar asked Dec 01 '11 12:12

Ankur


People also ask

How do I give an action to a button in IOS Swift?

Set Button Action When the button is tapped we can make it call a function. To add an action call to our button we will need to use the addTarget() function.

How can I check if UIButton is pressed?

You can use the following code. class ViewController: UIViewController { var gameTimer: Timer! @IBAction func btnClick(_ sender: Any) { let button = UIButton() if (button. isSelected) { print(" Not Selected"); } else { print(" Selected"); } } override func viewDidLoad() { super.

How do I delete all targets UIButton?

Call removeTarget:action:forControlEvents:, pass nil for the target, NULL for action, and use a control mask that sets all bits (UIControlEventAllEvents). Aside: the -allTargets instance method returns an NSSet of all the instance's targets (nil if none).

What is UIButton Swift?

A control that executes your custom code in response to user interactions.


3 Answers

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];
like image 136
Wolverine Avatar answered Sep 30 '22 21:09

Wolverine


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

action:@selector(buttonClick:)
like image 29
EmptyStack Avatar answered Sep 30 '22 21:09

EmptyStack


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{

}
like image 45
Vvk Avatar answered Sep 30 '22 22:09

Vvk