1,手势识别器简介
在iOS中由于手势识别器的存在,我们可以非常容易的识别出用户的交互手势。 系统提供的手势识别器如下:
- UITapGestureRecognizer (点一下)
- UIPinchGestureRecognizer(二指往內或往外拨动,平时经常用到的缩放)
- UIRotationGestureRecognizer(旋转)
- UISwipeGestureRecognizer(滑动,快速移动)
- UIPanGestureRecognizer(拖移,慢速移动)
- UILongPressGestureRecognizer(长按)
大家对上面的手势识别器肯定不陌生, 那么问题来了:
1,手势识别器是怎样识别出用户手势的?
2,如何使用手势识别器?
3,各手势识别器状态,及各状态间如何进展?
4,多个手势识别器作用在同一个UIView会发生什么?
5,如何通过继承现有手势识别器来自定义?
围绕着这几个问题, 咱们一起深入的学习一下 GestureRecognizer。
2, 解释触摸
2.1手势识别和Touch event 的关系:
手势识别通过分析 Touch events 中的数据, 识别出当前当前手指的动作。 成功识别出手势后,发送 Action message。了解手势识别器如何解释触摸还是有好处的: 你可以利用Touch event中的数据直接解释触摸; 继承现有的手势识别器满足特定的识别需求。
2.2通过几段代码解释如何解释触摸:
自定义一个view, 然后重写下面的 touches… 方法。 然后将这个view 添加到superView中。 为了简单,只考虑一个手指。
2.2.1,手指拖动视图
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
let loc = (touches as NSSet).anyObject()?.locationInView(self.superview)
let oldP = (touches as NSSet).anyObject()?.previousLocationInView(self.superview)
let deltaX = (loc?.x)! - (oldP?.x)!
let deltaY = (loc?.y)! - (oldP?.y)!
var c = self.center
c.x += deltaX
c.y += deltaY
self.center = c
}
2.2.2, 添加限制, 只可以水平或者垂直的拖动视图。
//定义两个属性,存储识别时的状态
var decided = false //是否确定移动方向了
var horiz = false //是否水平移动
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
decided = false
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
if !decided { //第一次调用, 确定移动的方向。
decided = true
let then = (touches as NSSet).anyObject()?.previousLocationInView(self.superview)
let now = (touches as NSSet).anyObject()?.locationInView(self.superview)
let deltaX = fabs((now?.x)! - (then?.x)!)
let deltaY = fabs((now?.y)! - (then?.y)!)
horiz = deltaX>=deltaY
}
let loc = (touches as NSSet).anyObject()?.locationInView(self.superview)
let oldP = (touches as NSSet).anyObject()?.previousLocationInView(self.superview)
let deltaX = (loc?.x)! - (oldP?.x)!
let deltaY = (loc?.y)! - (oldP?.y)!
var c = self.center
if horiz{
c.x += deltaX
}else{
c.y += deltaY
}
self.center = c
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
}
2.2.3,区分长按和短按
区分长按和短按主要根据 touchesBegan,touchesEnded之间的时间间隔确定。 UITouch 对象的timestamp属性能够得到点击时的时间间隔。 代码如下:
var time:Double = 0 //记录时间开始时的时间
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
time = (touches.first?.timestamp)!
}
override func touchesM