背景
我以前学习过如何使用手势识别器或continueTrackingWithTouch
获取当前触摸位置的持续更新,然后使用这些来执行以下操作:
然而,现在我想学习如何使用目标来做同样的事情。我已经可以使用TouchDown
and来获取 touch down 和 touch up 事件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:添加此答案的目标部分提供完整答案。