Button click detection in Swift

How can I detect clicks on the next element UIKitin Swift on the Xcode 6 Playground?

let testLabel = UILabel(frame: CGRectMake(0, 0, 120, 40))
testLabel.text = "My Button"
+4
source share
2 answers

The class is UILabelused to display text on the screen. Of course, you can detect taps (not clicks) on it, but theres a UIKitclass specifically designed to handle actions on the screen, and that UIButton.

Note. The playground is designed to test logic in your code, not events. If you want to play with specific iOS content, try creating a Single View app project in the iOS section of Xcode 6.

UIButton, , iOS 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)

ViewController buttonTapped:

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

Swift 3, UIButton - UIControl - addTarget(_:action:for:). addTarget(_:action:for:) :

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

.


:

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 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 timeline
let vc = ViewController()
PlaygroundPage.current.liveView = vc
0

All Articles