【问题标题】:How do I add a IBAction to a button programmatically in Swift 4?如何在 Swift 4 中以编程方式将 IBAction 添加到按钮?
【发布时间】:2017-10-26 08:59:51
【问题描述】:

如何以编程方式将 IBAction 添加到按钮?

button.addTarget(self, action: Selector(("buttonAction:")), for: 
.touchUpInside)

func buttonAction(sender: Any) {
    print("test")
}

这给了我一个“Thread 1: signal SIGABRT”错误。

【问题讨论】:

  • “您在代码中删除了 Outlet/Action 连接或重命名了它(拼写错误?)。” - 不是的情况:')
  • btn.addTarget(self, action: #selector(testFunction(_:)), for: .touchDown) swift 3.2
  • 从技术上讲,您不会以编程方式“添加”IBAction - “IB”代表“Interface Builder”。您要问的是如何在addTarget(action:) 调用中使用sender

标签: ios swift xcode uibutton


【解决方案1】:

Swift 4 版本:

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

@objc private func action(sender: Button) {
    print("test")
}

【讨论】:

  • 感谢您的回复,是的,我以前看过这段代码。但是 Swift 对我大喊:“'#selector' 的参数指的是未暴露给 Objective-C 的实例方法 'buttonAction(sender:)' 添加 '@objc' 以将此实例方法暴露给 Objective-C "
  • 这就是为什么会有@objc 注释
  • @Mofawaw 然后添加“@objc”,应该看起来像“@objc func buttonAction()”
  • @objc func action(sender: Button)
  • 我不得不等待 2 分钟,而不是我的编程。 :')
猜你喜欢
  • 1970-01-01
  • 2021-10-04
  • 1970-01-01
  • 1970-01-01
  • 2016-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多