如何在Xcode 6游乐场中检测Swift中以下UIKit
元素的点击次数?
let testLabel = UILabel(frame: CGRectMake(0, 0, 120, 40))
testLabel.text = "My Button"
答案 0 :(得分:13)
UILabel
类仅用于在屏幕上显示文本。当然你可以检测到它上面的点击(而不是点击),但是有一个UIKit
类可以专门用来处理屏幕上的操作,那就是UIButton
。
注意:游乐场旨在让您在代码中测试逻辑,而不是事件。如果你想玩iOS特定的东西,尝试在Xcode 6的iOS部分下创建一个单视图应用程序项目。
实现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!")
}
答案 1 :(得分:0)
使用Swift 3,UIButton
- 作为UIControl
的子类 - 有一个名为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