Danial Kosarifa Danial Kosarifa - 16 days ago 5
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() {

//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)

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


func buttonPressed(sender: UIButton!) {


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


You were close. Just replace

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

with this:

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