iOS手势识别:识别原理和自定义手势识别

1,手势识别器简介

在iOS中由于手势识别器的存在,我们可以非常容易的识别出用户的交互手势。 系统提供的手势识别器如下:

大家对上面的手势识别器肯定不陌生, 那么问题来了:

1,手势识别器是怎样识别出用户手势的?
2,如何使用手势识别器?
3,各手势识别器状态,及各状态间如何进展?
4,多个手势识别器作用在同一个UIView会发生什么?
5,如何通过继承现有手势识别器来自定义?

围绕着这几个问题, 咱们一起深入的学习一下 GestureRecognizer。


2, 解释触摸

2.1手势识别和Touch event 的关系:

手势识别与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
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值