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)"
}
2
Answers
The name of the method is
plusOne(sender:)
, the argument labels make part of the nameThe 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.