在Swift中检测按钮点击

9

在Xcode 6 playground中,我如何检测以下UIKit元素的点击事件?

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

2
你为什么不使用UIButton呢? - Mick MacCallum
2
除此之外,我对Swift还很陌生。有没有一种简单的方法来检测UIButton上的点击? - hawkharris
1
是的,这就是它的意图。以下是一个编程示例,展示如何通过程序创建一个。https://dev59.com/Y2Af5IYBdhLWcg3w9mps#24102198 - Mick MacCallum
1
@hawkharris FYI:您可以使用UITapGestureRecognizer检测UILabel上的点击,但是在这种情况下,使用UIButton更有意义。 - Lyndsey Scott
2个回答

13
UILabel类仅用于在屏幕上显示文本。当然,您可以在其上检测点按(而不是点击),但是有一个专门处理屏幕上操作的UIKit类,即UIButton
注意:Playground旨在测试代码中的逻辑,而不是事件。如果您想尝试玩iOS特定的东西,请尝试在Xcode 6下iOS部分中创建Single View Application项目。
实现一个UIButton,假设你正在Xcode的iOS项目内部:
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!")
}

Swift 2.2使用--button.addTarget(self, action: #selector(ViewController.buttonTapped), forControlEvents: .TouchUpInside) - uplearned.com

2

在Swift 3中,UIButtonUIControl的子类,具有一个名为addTarget(_:action:for:)的方法。 addTarget(_:action:for:)的声明如下:

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

将目标对象和操作方法与控件关联。
以下Playground代码展示了如何检测按钮的点击:
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接