创建一个继承自UITouch的类

时间:2016-11-17 21:50:24

标签: swift timestamp uitouch touchesbegan nstimeinterval

我正在使用Swift 3和Xcode

我有以下课程:

class Finger: UITouch
{
    var firstTimeStamp: TimeInterval = 0.0
}

和这个变量:

var finger: Finger?

这是我的touchesBegan函数:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
{
    if finger == nil
    {
        let touch = touches.first
        finger = touch as! GameScene.Finger?    <--- ERROR
        finger?.firstTimeStamp = finger!.timestamp
    }
}

它构建,但当我触摸屏幕时,我收到此错误: Could not cast value of type 'UITouch' (0x10f3b1ca8) to 'Project.GameScene.Finger' (0x10c3f71a0).

我试图知道手指在屏幕上的时间,从touchesBegan到touchesEnded。这是最好的方法吗? 无论如何,我做错了什么?

1 个答案:

答案 0 :(得分:0)

我在UIViewController中插入下面的代码。

方式1

var touchBeginDate:Date?

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    print("touchesBegan")
    if touchBeginDate == nil {
        touchBeginDate = Date()
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

    if let touchBeginDate = touchBeginDate {

        let calendar = Calendar.current
        let components = calendar.dateComponents([Calendar.Component.second, Calendar.Component.minute], from: touchBeginDate, to: Date())
        print("\(components)")
    }

    touchBeginDate = nil
    print("touchesEnded")
}

结果

enter image description here

方式2

class TapGestureRecognizer: UILongPressGestureRecognizer {
    var touchBeginDate:Date?
}

class ViewController: UIViewController, UIGestureRecognizerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        let tapGestureRecognizer = TapGestureRecognizer(target: self, action: #selector(ViewController.action(tapGestureRecognizer:)))
        tapGestureRecognizer.delegate = self
        tapGestureRecognizer.delaysTouchesBegan = false
        tapGestureRecognizer.delaysTouchesEnded = false
        view.addGestureRecognizer(tapGestureRecognizer)
    }

    func action(tapGestureRecognizer: TapGestureRecognizer) {
        switch tapGestureRecognizer.state {
        case .began:
            print("touch began")
            if tapGestureRecognizer.touchBeginDate == nil {
                tapGestureRecognizer.touchBeginDate = Date()
            }
        case .ended:
            if let touchBeginDate = tapGestureRecognizer.touchBeginDate {
                let calendar = Calendar.current
                let components = calendar.dateComponents([Calendar.Component.second, Calendar.Component.minute], from: touchBeginDate, to: Date())
                print("\(components)")
            }
            tapGestureRecognizer.touchBeginDate = nil
            print("touch ended")
        case .cancelled:
            break
        case .failed:
            break
        case .possible:
            break
        case .changed:
            break
        }
    }
}