Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stuck with adding target to button programmatically

I've created a UIButton and I want it to print some message when it's pressed.

So I did something like this: In loadView()

button.addTarget(self, action: #selector(ViewController.pressButton(button:)), for: .touchUpInside)

A method:

func pressButton(button: UIButton) {

    NSLog("pressed!")

}

But nothing happens when I click the button.

like image 797
user234159 Avatar asked Oct 02 '16 08:10

user234159


4 Answers

Add the button code in your viewDidLoad and it will work for you:

override func viewDidLoad() {
    super.viewDidLoad()
    let button = UIButton(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
    button.backgroundColor = UIColor.gray
    button.addTarget(self, action: #selector(pressButton(button:)), for: .touchUpInside)
    self.view.addSubview(button)
}

func pressButton(button: UIButton) {
    NSLog("pressed!")
}

You don´t need to add ViewController.pressButton to selector, it´s enough with the function name.

Swift 4.x version:

let button = UIButton(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
button.backgroundColor = .gray
button.tag = 0
button.addTarget(self, action: #selector(pressButton(_:)), for: .touchUpInside)
self.view.addSubview(button)

@objc func pressButton(_ button: UIButton) {
    print("Button with tag: \(button.tag) clicked!")
}

Swift 5.1 version:

let button = UIButton(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
button.backgroundColor = .gray
button.tag = 100
button.addTarget(self, action: #selector(pressButton), for: .touchUpInside)
self.view.addSubview(button)

@objc func pressButton(button: UIButton) {
    print("Button with tag: \(button.tag) clicked!")
}
like image 112
Rashwan L Avatar answered Nov 04 '22 03:11

Rashwan L


try this in Swift3!

button.addTarget(self, action: #selector(self.pressButton(button:)), for: .touchUpInside)

@objc func pressButton(button: UIButton) { NSLog("pressed!") }
like image 7
Otis Lee Avatar answered Nov 04 '22 03:11

Otis Lee


Use the following code.

button.addTarget(self, action: #selector(FirstViewController.cartButtonHandler), for: .touchUpInside)

Your class name corresponds to FirstViewController

And your selector corresponds to the following function

func cartButtonHandler() {

}
like image 5
arango_86 Avatar answered Nov 04 '22 03:11

arango_86


In swift 3 use this -

object?.addTarget(objectWhichHasMethod, action: #selector(classWhichHasMethod.yourMethod), for: someUIControlEvents)

For example(from my code) -

self.datePicker?.addTarget(self, action:#selector(InfoTableViewCell.datePickerValueChanged), for: .valueChanged)

Just give a : after method name if you want the sender as parameter.

like image 3
Nikhil Manapure Avatar answered Nov 04 '22 03:11

Nikhil Manapure