背景
我之前学过如何使用手势识别器或 continueTrackingWithTouch
来连续更新当前触摸位置,并将其用于执行类似以下操作的操作:
TouchDown
和TouchUpInside
获取触摸按下和触摸抬起事件,但我不知道如何获取连续更新。我假设应该使用ValueChanged
事件,但到目前为止还没有起作用。
这是我尝试过的:
ViewController.swift
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myCustomControl: MyCustomControl!
@IBOutlet weak var trackingBeganLabel: UILabel!
@IBOutlet weak var trackingEndedLabel: UILabel!
@IBOutlet weak var xLabel: UILabel!
@IBOutlet weak var yLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// these work
myCustomControl.addTarget(self, action: "myTouchDown", forControlEvents: UIControlEvents.TouchDown)
myCustomControl.addTarget(self, action: "myTouchUpInside", forControlEvents: UIControlEvents.TouchUpInside)
// this doesn't work
myCustomControl.addTarget(self, action: "myValueChangedEvent:",
forControlEvents: UIControlEvents.ValueChanged)
}
// this works
func myTouchDown() {
trackingBeganLabel.text = "Touched down"
}
// this works
func myTouchUpInside() {
trackingEndedLabel.text = "Touch up inside"
}
// this doesn't work, function never gets called
func myValueChangedEvent(sender: UIControl) {
let location = sender.convertPoint(CGPointZero, toView: myCustomControl)
xLabel.text = "x: \(location.x)"
yLabel.text = "y: \(location.y)"
}
}
MyCustomControl.swift
import UIKit
class MyCustomControl: UIControl {
// currently empty. Do I need to add something here?
}
注意事项
- 在得到@CaseyWagner的答案后更改了代码。编译器不再抛出错误,但
UIControlEvents.ValueChanged
从未被触发。 - 这个问题是我尝试为这个答案中的方法1:添加目标部分提供完整答案。
if let touch = ...
,因为我不确定强制解包是否会导致崩溃。 - Suragch