如何使用给定函数的 @objc 标记在代码中分配按钮的操作?
您好,对于这个问题,我在 如何以编程方式创建按钮? 上找到了答案仍然面临错误:“‘#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)"
}
Hi for this question I found answer on How to create a button programmatically? however still facing the errors: "Argument of '#selector' cannot refer to local function 'plusOne(sender:)'" and "@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes". If you can advice.
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)"
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您遇到的问题是您将
@objc func plusOne(sender: UIButton!)
嵌套在viewDidLoad
中(这就是我问有关范围的最初问题的原因)。您需要将其移至类范围方法中。The problem you have is that you've nested the
@objc func plusOne(sender: UIButton!)
withinviewDidLoad
(which was why i asked the initial question about scope). You need to move it out to a class-scope method.该方法的名称是
plusOne(sender:)
,参数标签构成名称的一部分The name of the method is
plusOne(sender:)
, the argument labels make part of the name