Danial Kosarifa Danial Kosarifa - 1 month ago 7
iOS Question

How to set a listener function for a button defined programatically in swift 3

I am trying to set a listener function for my button but I keep getting error . Here is how've done it :

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()


//Create the BackGround
self.view.backgroundColor = UIColor.black
let startButton = UIButton()
startButton.setTitle( " start ", for: UIControlState.normal)
startButton.setTitleColor(UIColor.blue, for: UIControlState.normal)
startButton.frame = CGRect(x: 10, y:40 , width: 250, height: 25)
self.view.addSubview(startButton)

startButton.addTarget(self, action: "buttonPressed:" , for: .touchUpInside)


}


func buttonPressed(sender: UIButton!) {
print("hello")
}


}


Does any one knows where am I making the mistake ? :)

Answer

You were close. Just replace

startButton.addTarget(self, action: "buttonPressed:" , for: .touchUpInside)

with this:

startButton.addTarget(self, action: #selector(ViewController.buttonPressed(sender:)) , for: .touchUpInside)