如何检测Swift 3中可见的UITouch位置

时间:2016-11-26 05:48:32

标签: swift uitouch

我正在尝试检测可见的UITouch事件。当触摸事件开始时。目前,我使用下面的代码来检测触摸位置。从下面的代码,我可以打印触摸位置。任何,非常感谢帮助。

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
{
    if let touch = touches.first {
        let position :CGPoint = touch.location(in: view)
        print(position.x)
        print(position.y)
    }
}

注意:我不是想绘制一条线或类似绘图应用的东西。我只想看到触摸事件。发生时。

提前致谢。

1 个答案:

答案 0 :(得分:1)

如果您想在用户点按屏幕时显示圆圈或其他内容,请尝试以下操作:

var touchIndicators: [UIView] = []
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        let location = touch.location(in: view)
        let touchIndicator = UIView(frame: CGRect(x: location.x - 10, y: location.y - 10, width: 20, height: 20))
        touchIndicator.alpha = 0.5
        touchIndicator.backgroundColor = UIColor.red
        touchIndicator.layer.cornerRadius = 10
        self.view.addSubview(touchIndicator)
        touchIndicators.append(touchIndicator)
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    for indicator in touchIndicators {
        indicator.removeFromSuperview()
    }
    touchIndicators = []
}

非常简单。当用户触摸屏幕时添加圆形视图,并在用户抬起他/她的手指时将其移除。您也可以使用UITapGestureRecognizer

执行此操作