触摸事件:

UITouch:一个手机第一次点击屏幕,会形成一个UITouch对象,知道离开销毁。表示触碰。UITouch对象能表明当前手指触碰的屏幕位置、状态,状态分为开始触碰、移动、离开。

具体方法介绍如下:

1.override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)

通知调用者当有一个或者多个手指触摸到了视图或者窗口时触发次方法,touches是UITouch的集合,通过uito我们可以检测触摸事件的属性,是单击还是双击,还有触摸的位置等。

2.override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?)

告诉接受者一个或者多个手指在视图或者窗口上触发移动事件。默认不允许多点触摸,如果要接受多点触摸事件必须将UIVIew属性置为true。

//支持多点触摸
self.view.isMultipleTouchEnabled = true

3.override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?)

当一个触摸事件结束时发出的UITouch实例对象

4.override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?)

通知接受者当系统发出取消事件的时候(如第内存消耗时的警告框)

样例代码:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch:AnyObject in touches {
let t:UITouch = touch as! UITouch
//当在屏幕上连续拍动两下时,背景回复为白色
if t.tapCount ==
{
self.view.backgroundColor = UIColor.white
}else if t.tapCount ==
{
self.view.backgroundColor = UIColor.blue
}
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
//获取点击的坐标位置
for touch:AnyObject in touches {
let t:UITouch = touch as! UITouch
print(t.location(in: self.view))
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if touches.count ==
{
//获取触摸点
let first = (touches as NSSet).allObjects[] as! UITouch
let second = (touches as NSSet).allObjects[] as! UITouch
//获取触摸点坐标
let firstPoint = first.location(in: self.view)
let secondPoint = second.location(in: self.view)
//计算两点间的距离
let deltaX = secondPoint.x - firstPoint.x
let deltaY = secondPoint.y - firstPoint.y
let initialDistance = sqrt(deltaX + deltaY * deltaY)
print("两点间的距离:\(initialDistance)")
//计算两点间的角度
let height = secondPoint.y - firstPoint.y
let width = firstPoint.x - secondPoint.x
let rads = atan(height/width)
let degrees = 180.0 * Double(rads) / .pi
print("两点间角度:\(degrees)")
}
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
print("event canceled!")
}
05-26 13:14