【问题标题】:How to create a UIButton programmatically in iOS 14 in objective-C?如何在 Objective-C 中的 iOS 14 中以编程方式创建 UIButton?
【发布时间】:2020-11-25 03:16:04
【问题描述】:

我正在尝试在 Objective-C 的 iOS 14(beta 3)中以编程方式创建 UIButton。这是我尝试过的,但是当我点击按钮时 UIAction 处理程序永远不会被调用:

UIAction *tapAction = [UIAction actionWithHandler:^(UIAction* action){
     NSLog(@"Never gets here");
}];
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100) primaryAction:tapAction];

有什么想法吗?

【问题讨论】:

  • 这不是重复的。我使用 addTarget 的旧代码在 iOS 14 上不起作用。目标永远不会被调用。我的理解是 iOS 14 通过要求 UIAction 改变了指定目标的方式。
  • 澄清一下,我使用的是 Xcode 12 beta 3。
  • macOS Big Sur 11.0 beta、Xcode 12.0 beta 4、iOS 14.0 beta 3 - 基于链接副本中的代码 - 对我来说很好 - 你的问题在其他地方
  • 是的,我发现问题是由于按钮位于表格视图单元格内。在 iOS 14 之前,会调用目标,但在 iOS 14 上不会。作为一种解决方法,我使用 didSelectRowAtIndexPath 并在单元格中找到按钮并直接调用目标。

标签: ios objective-c uibutton uiaction


【解决方案1】:

我有同样的问题。对我来说它看起来像一个错误。尝试添加:

 self.contentView.isUserInteractionEnabled = true

init(style:reuseIdentifier:) 如果您使用的是自定义 tableview 单元格。请参考https://developer.apple.com/forums/thread/661508?page=1#636261022 和@OOPer 很好的答案。

【讨论】:

    【解决方案2】:

    我编写了一个测试应用程序,它只显示一个按钮并且它正在工作,所以问题一定是我的主应用程序中的其他问题。谢谢大家。

    【讨论】:

      【解决方案3】:

      这就是我通常在 Objective-C 中创建按钮的方式:

      - (void)createButton {
          UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
          button.frame = CGRectMake(0, 0, 50, 100);
          [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
      }
          
      - (void)buttonClicked:(UIButton *)sender {
         // Do your logic here
      }
      

      您可以在此处阅读更多内容: https://developer.apple.com/documentation/uikit/uicontrol/1618259-addtarget

      【讨论】:

      • 这是我的旧代码所做的,但在 iOS 14 上它无法到达选择器。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-27
      • 1970-01-01
      • 1970-01-01
      • 2015-01-09
      • 1970-01-01
      • 2014-01-06
      相关资源
      最近更新 更多