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"
func buttonTapped() { println("Button tapped!") }
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.
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!") }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With