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

后端 未结 10 1234
野的像风
野的像风 2020-11-29 21:40

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

相关标签:
10条回答
  • 2020-11-29 21:59
    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 
    
    }
    
    0 讨论(0)
  • 2020-11-29 22:00

    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
    }
    
    0 讨论(0)
  • 2020-11-29 22:05

    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)
    
    0 讨论(0)
  • 2020-11-29 22:11

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

    0 讨论(0)
提交回复
热议问题