Detecting clicks on a button in Swift

i0S Swift Issue

Question or problem in the Swift programming language:

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"

How to solve the problem:

Solution 1:

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!")

Solution 2:

With Swift 3, UIButton – as a subclass of UIControl – has a method called addTarget(_:action:for:). addTarget(_:action:for:) has the following declaration:

func addTarget(_ target: Any?, action: Selector, for controlEvents: UIControlEvents)

Associates a target object and action method with the control.

The Playground code below shows how to detect a click on a button:

import PlaygroundSupport import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white // Create button let button = UIButton(type: UIButtonType.system) button.setTitle("Click here", for: UIControlState.normal) // Add action to button button.addTarget(self, action: #selector(buttonTapped(sender:)), for: UIControlEvents.touchUpInside) // Add button to controller's view view.addSubview(button) // Set Auto layout constraints for button button.translatesAutoresizingMaskIntoConstraints = false let horizontalConstraint = button.centerXAnchor.constraint(equalTo: view.centerXAnchor) let verticalConstraint = button.centerYAnchor.constraint(equalTo: view.centerYAnchor) NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint]) } // trigger action when button is touched up func buttonTapped(sender: UIButton) { print("Button was tapped") } } // Display controller in Playground's timeline let vc = ViewController() PlaygroundPage.current.liveView = vc 

Hope this helps!