Ios – Detecting clicks on a button in Swift


How can I detect clicks on the following UIKit element in Swift, in an Xcode 6 playground?

let testLabel = UILabel(frame: CGRectMake(0, 0, 120, 40))
testLabel.text = "My Button"

Best Solution

The UILabel class is used just to display text on the screen. Sure you can detect taps (not clicks) on it, but theres a UIKit class specifically crafted to handle actions on the screen, and that's UIButton.

Note: A playground is intended for you to test logic, not events, in your code. If you want to play around with iOS specific stuff, try creating a Single View Application Project under the iOS section from Xcode 6.

Implementing a UIButton, assuming you're inside an iOS Project on Xcode:

var button = UIButton(frame: CGRect(x: 0, y: 0, width: 150, height: 60))
button.backgroundColor = UIColor.blackColor()
button.layer.cornerRadius = 3.0
button.setTitle("Tap Me", forState: .Normal)
button.addTarget(self, action: "buttonTapped", forControlEvents: .TouchUpInside)

Then, on the same ViewController class, create the buttonTapped method:

func buttonTapped() {
    println("Button tapped!")