背景
I've 以前学过的 https://stackoverflow.com/a/34764356/3681880如何使用手势识别器或continueTrackingWithTouch
获取当前触摸位置的持续更新,然后使用它们执行如下操作:
然而现在,我想学习如何使用目标来做同样的事情。我已经可以通过使用来获得触地和触地事件TouchDown
and 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?
}
Notes
- 得到@CaseyWagner的答案后更改了代码。编译器不再抛出错误,但是
UIControlEvents.ValueChanged
永远不会被解雇。
- 这个问题是我试图得到一个完整的答案方法一:添加目标的部分这个答案 https://stackoverflow.com/a/34764356/3681880.
Use UIControlEvents.TouchDragInside
代替UIControlEvents.ValueChanged
(另请注意,操作方法接收两个参数):
myCustomControl.addTarget(self, action: "didDragInsideControl:withEvent:",
forControlEvents: UIControlEvents.TouchDragInside)
处理函数如下所示:
func didDragInsideControl(control: MyCustomControl, withEvent event: UIEvent) {
let touch = event.touchesForView(control)!.first!
let location = touch.locationInView(control)
xLabel.text = "x: \(location.x)"
yLabel.text = "y: \(location.y)"
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)