【问题标题】:How do you add an action to a button programmatically in xcode如何在 xcode 中以编程方式向按钮添加操作
【发布时间】:2011-08-16 03:38:06
【问题描述】:

我知道如何通过从界面构建器中拖动来将 IBAction 添加到按钮,但我想以编程方式添加操作以节省时间并避免不断来回切换。解决方案可能非常简单,但是当我搜索它时似乎找不到任何答案。谢谢!

【问题讨论】:

    标签: ios iphone objective-c uibutton programmatically-created


    【解决方案1】:

    试试这个:

    斯威夫特 4

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

    Objective-C

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

    您可以在 Apple 的文档中找到丰富的信息来源。看看UIButton's documentation,它会发现UIButton是UIControl,的后代,它实现了add targets的方法。

    --

    需要注意myAction后面是否加冒号 action:@selector(myAction)

    这是reference

    【讨论】:

    • 如果我想在按下按钮时将参数传递给选择器怎么办(例如,我在 UITableViewCell 中有一个按钮,并且我想在按下单元格的按钮时传递该单元格中的对象)?
    • @acecapades 我认为您将两件事混为一谈。您不能像使用 performSelector 那样附加参数。 UIControl 后代 UIButton 使用的动作模式是在触发 controlEvent 时用特定选择器通知某些目标。当您的情况发生这种情况时,您可以查看超级视图以查看谁在封装您的按钮并询问一种方法来将表格单元格解析为模型关系,然后用它做任何您想做的事情。
    • 我明白了。这就说得通了。我想我明白你在说什么。感谢尼克的提示!
    • 有人能快速翻译一下吗?
    【解决方案2】:

    快速回答:

    myButton.addTarget(self, action: "click:", for: .touchUpInside)
    
    func click(sender: UIButton) {
        print("click")
    }
    

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

    【讨论】:

    • UIControl.addTarget 调用中“单击”后的“:”是什么?
    • 选择器有一个: 作为函数参数的占位符。由于click 采用sender 参数,因此在选择器字符串中将其替换为:
    • 这最近对我来说适用于 Swift 3。 button.addTarget(self, action: #selector(ViewController.click), for: UIControlEvents.touchUpInside) func click() { print("click")感谢@Glauco Neves 为我们指明了正确的方向
    【解决方案3】:
    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];
    

    【讨论】:

    • 是否可以添加 2 个或更多操作?
    【解决方案4】:

    试试这个:

    首先将其写入您的视图控制器的 .h 文件中

    UIButton *btn;
    

    现在将其写入您的视图控制器 viewDidLoad 的 .m 文件中。

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

    在视图控制器的 .m 文件中写入这个外部 viewDidLoad 方法

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

    【讨论】:

      【解决方案5】:
       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 }
      

      【讨论】:

        【解决方案6】:

        对于 Swift 3

        首先为按钮操作创建一个函数,然后将该函数添加到您的按钮目标

        func buttonAction(sender: UIButton!) {
            print("Button tapped")
        }
        
        button.addTarget(self, action: #selector(buttonAction),for: .touchUpInside)
        

        【讨论】:

          【解决方案7】:
          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 
          
          }
          

          【讨论】:

          • 请提供一些 cmets 解释您的样本如何提供帮助。
          • 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 { // 这里可以写功能 }
          • -(void)btnClicked { //在这里你可以设置按钮的动作 //示例:转到下一个视图控制器 nextviewController *nextPage=[nextviewController alloc]init]; [self.navigationController pushviewcontroller:nextPage 动画:YES ]; }
          【解决方案8】:

          UIButton 继承自 UIControl。这具有添加/删除操作的所有方法:UIControl Class Reference。查看“准备和发送操作消息”部分,其中涵盖了– sendAction:to:forEvent:– addTarget:action:forControlEvents:

          【讨论】:

            【解决方案9】:
             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];   
            

            【讨论】:

              【解决方案10】:

              IOS 14 SDK: 您可以使用闭包回调添加操作:

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

              获取对控制发送者的引用

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

              source

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2018-01-24
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多