0

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)"
}
mairo
  • 155
  • 8
  • 2
    Where does this code sit? Is it in a viewController, or related object, or are you trying to wrie this at a global level within a playground? – flanker Mar 01 '22 at 00:01
  • @flanker git@github.com:Mairoslav/ClickCounter.git the code is in override func viewDidLoad() {... within class ViewController: UIViewController { in ViewController – mairo Mar 01 '22 at 11:21

2 Answers2

1

The problem you have is that you've nested the @objc func plusOne(sender: UIButton!) within viewDidLoad (which was why i asked the initial question about scope). You need to move it out to a class-scope method.

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)"
}
flanker
  • 3,840
  • 1
  • 12
  • 20
0

The name of the method is plusOne(sender:), the argument labels make part of the name

Nathan Day
  • 5,981
  • 2
  • 24
  • 40
  • I tried to write the function as per your suggestion action: #selector(incrementCount(sender:)) still could not work it out. git@github.com:Mairoslav/ClickCounter.git – mairo Mar 01 '22 at 11:32
  • 2
    @mairo - move your function outside the `viewDidLoad` Button handler should not be within the scope of another function. – Shawn Frank Mar 01 '22 at 11:38
  • @Nathan Day While correct in the naming of the method, you don't need to specify the labels when using in a `#selector`. For example `button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)` is valid for a method with signature `@objc private func buttonTapped(sender: UIButton)` – flanker Mar 01 '22 at 11:42
  • thank you @shawnfrank for useful help, I am careful about this now. Cheers. – mairo Mar 01 '22 at 11:53