如何使用@objc 标记为给定功能分配代码中的按钮操作?

How to assign a button’s action in code using @objc mark for given function?

您好,这个问题我在 How to create a button programmatically? 上找到了答案,但仍然面临错误:“'#selector' 的参数不能引用本地函数 'plusOne(sender:)'”和“@objc 只能使用与 类 的成员、@objc 协议和 类 的具体扩展”。如果你能指点一下。

let button = UIButton()
button.frame = CGRect(x: 150, y: 300, width: 60, height: 60)
button.setTitle("Click", for: .normal)
button.setTitleColor(UIColor.blue, for: .normal)
button.addTarget(self, action: #selector(plusOne), for: .touchUpInside)
self.view.addSubview(button)
    
@objc func plusOne(sender: UIButton!) {
    self.count += 1 
    self.label.text = "\(self.count)"
}

方法的名称是plusOne(sender:),参数标签构成名称的一部分

您遇到的问题是您将 @objc func plusOne(sender: UIButton!) 嵌套在 viewDidLoad 中(这就是为什么我问了关于范围的最初问题)。您需要将其移出到 class-scope 方法。

override func viewDidLoad() {
  // all the usual stuff...

  let button = UIButton()
  button.frame = CGRect(x: 150, y: 300, width: 60, height: 60)
  button.setTitle("Click", for: .normal)
  button.setTitleColor(UIColor.blue, for: .normal)
  button.addTarget(self, action: #selector(plusOne), for: .touchUpInside)
  self.view.addSubview(button)

}

@objc func plusOne(sender: UIButton!) {
    self.count += 1 
    self.label.text = "\(self.count)"
}