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

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!

The answer is


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];

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


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 

}

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
}

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.


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)

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


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:.


 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];   

 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 }

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to iphone

Detect if the device is iPhone X Xcode 8 shows error that provisioning profile doesn't include signing certificate Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone Certificate has either expired or has been revoked Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve? cordova run with ios error .. Error code 65 for command: xcodebuild with args: "Could not find Developer Disk Image" Reason: no suitable image found iPad Multitasking support requires these orientations How to insert new cell into UITableView in Swift

Examples related to objective-c

Adding a UISegmentedControl to UITableView Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Warp \ bend effect on a UIView? Use NSInteger as array index Detect if the device is iPhone X Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3 ITSAppUsesNonExemptEncryption export compliance while internal testing? How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem? Change status bar text color to light in iOS 9 with Objective-C

Examples related to uibutton

How to make a simple rounded button in Storyboard? How to set the title text color of UIButton? How can I make a button have a rounded border in Swift? How to change UIButton image in Swift Changing text of UIButton programmatically swift Disable a Button How to change font of UIButton with Swift Attach parameter to button.addTarget action in Swift Change button background color using swift language Make a UIButton programmatically in Swift

Examples related to programmatically-created

Is there a way to programmatically scroll a scroll view to a specific edit text? How do you add an action to a button programmatically in xcode How do I create a basic UIButton programmatically?