如何获得触摸从ValueChanged事件斯威夫特坐标
我已经previously learned如何使用手势识别或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的答案后更改了代码。编译器不会再抛出错误,但不会被解雇。
- 这个问题是我试图对方法1:添加一个目标部分this answer的完整答案。
使用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)"
}
没有看到你的代码的其余部分,它看起来像你可能需要:
let location = sender.convertPoint(CGPointZero, toView: myCustomControl)
我更新了我的问题。 – Suragch
- 评论
@UIApplicationMain
线AppDelegate
-
创建名为主要的新文件。迅速,在该方法 进口的UIKit
class AppClass: UIApplication { override func sendEvent(event: UIEvent) { super.sendEvent(event) print("send event") // this is an example // ... dispatch the message... } }
-
写下面的代码文件
import UIKit import Foundation UIApplicationMain(Process.argc, Process.unsafeArgv, NSStringFromClass(AppClass), NSStringFromClass(AppDelegate))
名称为 “AppClass” 创建新类的UIApplication的子类中添加以下代码在这里,在sendEvent方法中,您将获得应用程序(所有屏幕)中发生的所有事件,所有触摸事件,因此您可以在此处使用此UIEvent并执行任何任务(如果需要)
太棒了!我错过了'TouchDragInside'事件。我用'if let touch = ...',因为我不确定强制解包是否会导致崩溃。 – Suragch