Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting clicks on a button in Swift

Tags:

ios

uilabel

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"
like image 821
hawkharris Avatar asked Aug 04 '14 23:08

hawkharris


People also ask

How do you check whether a button is clicked or not in Swift?

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

Why button is not clickable in Swift?

If your subview has a frame of size zero, you won't be able to tap the button even if you can see it. Using a view debugger from Xcode will show you if this is the issue. Also, check if the subview has user interaction enabled when adding it. Save this answer.

What is swift button?

SwiftUI's button is similar to UIButton , except it's more flexible in terms of what content it shows and it uses a closure for its action rather than the old target/action system. To create a button with a string title you would start with code like this: Button("Button title") { print("Button tapped!") }


1 Answers

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
like image 160
Imanou Petit Avatar answered Oct 15 '22 13:10

Imanou Petit