背景
我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?
}
备注
UIControlEvents.ValueChanged
永远不会被触发。答案 0 :(得分:10)
使用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)"
}
处理程序函数如下所示:
domain.com?someKey=someValue&someOtherKey=someOtherValue
答案 1 :(得分:1)
如果没有看到其他代码,看起来您可能需要:
let location = sender.convertPoint(CGPointZero, toView: myCustomControl)
答案 2 :(得分:1)
@UIApplicationMain
AppDelegate
行
创建名为main.swift的新文件,并将该代码添加到该文件中
import UIKit
import Foundation
UIApplicationMain(Process.argc, Process.unsafeArgv, NSStringFromClass(AppClass), NSStringFromClass(AppDelegate))
创建名为" AppClass"的新类和UIApplication的子类
在该方法中编写以下代码 导入UIKit
class AppClass: UIApplication {
override func sendEvent(event: UIEvent)
{
super.sendEvent(event)
print("send event") // this is an example
// ... dispatch the message...
}
}
这里,在sendEvent方法中,您将获得应用程序(所有屏幕)中发生的所有事件,所有触摸事件,所以在这里您可以使用此UIEvent并执行任何任务(如果需要)