How do you add an action to a button programmatically in xcode

IosIphoneObjective CUibuttonProgrammatically Created

Ios Problem Overview


I know how to add an IBAction to a button by dragging from the interface builder, but I want to add the action programmatically to save time and to avoid switching back and forth constantly. The solution is probably really simple, but I just can't seem to find any answers when I search it. Thank you!

Ios Solutions


Solution 1 - Ios

Try this:

Swift 4

myButton.addTarget(self,
                   action: #selector(myAction),
                   for: .touchUpInside)

Objective-C

[myButton addTarget:self 
             action:@selector(myAction) 
   forControlEvents:UIControlEventTouchUpInside];

You can find a rich source of information in Apple's Documentation. Have a look at the UIButton's documentation, it will reveal that UIButton is a descendant of UIControl, which implements the method to add targets.

--

You'll need to pay attention to whether add colon or not after myAction in action:@selector(myAction)

Here's the reference.

Solution 2 - Ios

Swift answer:

myButton.addTarget(self, action: "click:", for: .touchUpInside)

func click(sender: UIButton) {
    print("click")
}

Documentation: https://developer.apple.com/documentation/uikit/uicontrol/1618259-addtarget

Solution 3 - Ios

CGRect buttonFrame = CGRectMake( 10, 80, 100, 30 );
		UIButton *button = [[UIButton alloc] initWithFrame: buttonFrame];
		[button setTitle: @"My Button" forState: UIControlStateNormal];
		[button addTarget:self action:@selector(btnSelected:) forControlEvents:UIControlEventTouchUpInside];
		[button setTitleColor: [UIColor redColor] forState: UIControlStateNormal];
[view addSubview:button];

Solution 4 - Ios

try this:

first write this in your .h file of viewcontroller

UIButton *btn;

Now write this in your .m file of viewcontrollers viewDidLoad.

btn=[[UIButton alloc]initWithFrame:CGRectMake(50, 20, 30, 30)];
[btn setBackgroundColor:[UIColor orangeColor]];
//adding action programatically
[btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];

write this outside viewDidLoad method in .m file of your view controller

- (IBAction)btnClicked:(id)sender
{
   //Write a code you want to execute on buttons click event
}

Solution 5 - Ios

 CGRect buttonFrame = CGRectMake( x-pos, y-pos, width, height );   //
 CGRectMake(10,5,10,10) 

 UIButton *button = [[UIButton alloc] initWithFrame: buttonFrame];
 
 button setTitle: @"My Button" forState: UIControlStateNormal];
 
 [button addTarget:self action:@selector(btnClicked:)  forControlEvents:UIControlEventTouchUpInside];
 
 [button setTitleColor: [UIColor BlueVolor] forState:
 UIControlStateNormal];
 
 [view addSubview:button];
 
 
 
 
 -(void)btnClicked {
    // your code }

Solution 6 - Ios

For Swift 3

Create a function for button action first and then add the function to your button target

func buttonAction(sender: UIButton!) {
    print("Button tapped")
}

button.addTarget(self, action: #selector(buttonAction),for: .touchUpInside)

Solution 7 - Ios

UIButton *btnNotification=[UIButton buttonWithType:UIButtonTypeCustom];
btnNotification.frame=CGRectMake(130,80,120,40);
btnNotification.backgroundColor=[UIColor greenColor];
[btnNotification setTitle:@"create Notification" forState:UIControlStateNormal];
[btnNotification addTarget:self action:@selector(btnClicked) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnNotification];


}

-(void)btnClicked
{
    // Here You can write functionality 

}

Solution 8 - Ios

UIButton inherits from UIControl. That has all of the methods to add/remove actions: UIControl Class Reference. Look at the section "Preparing and Sending Action Messages", which covers – sendAction:to:forEvent: and – addTarget:action:forControlEvents:.

Solution 9 - Ios

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

Solution 10 - Ios

IOS 14 SDK: you can add action with closure callback:

let button = UIButton(type: .system, primaryAction: UIAction(title: "Button Title", handler: { _ in
            print("Button tapped!")
        }))

Getting a reference to the control sender

let textField = UITextField()
textField.addAction(UIAction(title: "", handler: { action in
    let textField = action.sender as! UITextField
    print("Text is \(textField.text)")
}), for: .editingChanged)

source

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionaggiesfan64View Question on Stackoverflow
Solution 1 - IosNick WeaverView Answer on Stackoverflow
Solution 2 - IosGlauco NevesView Answer on Stackoverflow
Solution 3 - IosDeveloperView Answer on Stackoverflow
Solution 4 - IoskrushnsinhView Answer on Stackoverflow
Solution 5 - IosiOSDeveloperView Answer on Stackoverflow
Solution 6 - IosSanRamView Answer on Stackoverflow
Solution 7 - Iosuser2677311View Answer on Stackoverflow
Solution 8 - IosodrmView Answer on Stackoverflow
Solution 9 - IosArjun SaView Answer on Stackoverflow
Solution 10 - IosUcdemirView Answer on Stackoverflow