You don’t need to add ()
to the end of a method when you are passing that method as a selector! This is because ()
is used to specify the arguments when you are calling the method. But you don’t want to call the method, do you? So remove the ()
!
//Adding BUtton
let btn = UIButton()
btn.frame = CGRect(x: 100, y: 100, width: 200, height: 100)
// () removed!
btn.addTarget(self, action: #selector(self.printname), for: UIControlEvents.touchUpInside)
self.view.addSubview(btn)
//Method to be called
func printname()
{
print("button pressed")
}
This is the same as passing a closure to a method:
doStuff(withClosure: myMethod)
func myMethod() {
// ...
}
This holds true no matter how many arguments there are in the method passed in.
EDIT: I just saw that your printname
method seems to be inside another method. If this is true, please move it to the class level! Also, you need to add a sender
argument to printname
:
func printname(sender: UIButton) {
// ...
}