iOS Review | UIGestureRecognizers手势

UIGestureRecognizer共有8种:

  • UITapGestureRecognizer
  • UIPanGestureRecognizerpan
  • UIScreenEdgePanRecognizer
  • UIPinchGestureRecognizer
  • UIRotationGestureRecognizer
  • UILongPressGestureRecognizer
  • UISwipeGestureRecognizer
  • UIGestureRecognizer即自定义手势

其用法大同小异,比较常用的主要有tap和pan,主要使用recognizer.locationrecognizer.view属性。

Storyboard上添加手势

UIPanGestureRecognizer

利用UIPanGesgtureRecognizer让view跟随touch移动,通常有两种处理逻辑。

  • 第一种利用recognizer.location
var offset: CGSize! // 记住一开始的touch point距离center的偏移值

// 事件回调
@IBAction func handlePan(recognizer : UIPanGestureRecognizer) {
    let location = recognizer.location(in: view)
    guard let view = recognizer.view else {
        return
    }
    switch recognizer.state {
        case .began:
// 计算并存储偏移值
            offset = CGSize(width: view.center.x - location.x, height: view.center.y - location.y)
// 偏移值 + location值即可做到跟随移动
        case .changed:
            view.center = CGPoint(x: offset.width + location.x, y: offset.height + location.y)
        default: break
    }
}
recognizer.location

这种方式虽然理解起来简单,但处理逻辑稍微繁琐点,不推荐使用。

  • 第一种利用recognizer.translation
@IBAction func handlePan(recognizer : UIPanGestureRecognizer) { 
// pan的移动偏移量--相对began时的点
    let translation = recognizer.translation(in: view)
    if let view = recognizer.view {
        view.center = CGPoint(x: view.center.x + translation.x, y: view.center.y + translation.y)
    }
// 在移动changed时,重置pan的上一次移动点为zero
    recognizer.setTranslation(.zero, in: view)
}

这种方式虽然使用简单,但要注意每次recognizer.setTranslation(.zero)归零,不然,一下子就让view移出了屏幕,因为translation每次就compound叠加的。

  • pan手势滑动的加速度velocity
if recognizer.state == .ended {
// 加速度
    let velocity = recognizer.velocity(in: self.view)
    let magnitude = sqrt(velocity.x * velocity.x + velocity.y * velocity.y)
    let slideMultiplier = magnitude / 200
    let slideFactor = 0.1 * slideMultiplier
    
// 最终点
    var finalPoint = CGPoint(x: view.center.x + (velocity.x * slideFactor), y: view.center.y + (velocity.y * slideFactor))
    let halfWidth = panView.bounds.width / 2
    let halfHeight = panView.bounds.height / 2
    finalPoint.x = min(self.view.bounds.width - halfWidth, max(halfWidth, finalPoint.x))
    finalPoint.y = min(self.view.bounds.height - halfHeight, max(halfHeight, finalPoint.y))
    
// 动画
    UIView.animate(withDuration: Double(slideFactor * 2), delay: 0, options: .curveEaseInOut, animations: {
        panView.center = finalPoint
    }, completion: nil)
}
加速度动画

UIPinchGestureRecognizer

  • 使用比较简单,利用recognizer.scale值即可transform要scale的view,但注意scale值也是连续变化的,注意随时将recognizer.scale归零。
  @IBAction func handlePinch(recognizer : UIPinchGestureRecognizer) {
    guard let pinchView = recognizer.view else {
        return
    }
    let scale = recognizer.scale
    pinchView.transform = pinchView.transform.scaledBy(x: scale, y: scale)
    recognizer.scale = 1 // 归零
  }

UIRotationGestureRecognizer

  • 使用和UIPinchGestureRecognizer一样,利用recognizer.rotation值即可transform要rotate的view,但注意rotation值也是连续变化的,注意随时将recognizer.rotation归零。
  @IBAction func handleRotate(recognizer : UIRotationGestureRecognizer) {
    guard let rotateView = recognizer.view else {
        return
    }
    let rotation = recognizer.rotation
    rotateView.transform = rotateView.transform.rotated(by: rotation)
    recognizer.rotation = 0
  }

Simultaneous Gesture Recognizers

  • 一般情况下,每个手势只能被单独使用,并不能在执行一个手势如rotation的同时执行scale手势,但可以设置UIGestureRecognizer的delegate,来配置是否允许手势同时执行。
extension ViewController: UIGestureRecognizerDelegate{
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
}

UITapGestureRecognizer

  • 这个手势相对来说是最常用的一个,实现方式也简单,常用recognizer.location属性和recognizer.view判断点击的view是否是目标view,然后处理不同的逻辑。
var chompPlayer: AVAudioPlayer? = nil
    
  override func viewDidLoad() {
    super.viewDidLoad()
    
    let filteredSubviews = view.subviews.filter{
        $0 is UIImageView
    }
// 给所有UIImageView添加tap手势
    for subview in filteredSubviews {
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap(recognizer:)))
        tapGestureRecognizer.delegate = self
        subview.addGestureRecognizer(tapGestureRecognizer)

// TODO:
    }
    
    chompPlayer = loadSound(filename: "chomp")
  }

// tap手势处理
@objc func handleTap(recognizer: UITapGestureRecognizer) {
    chompPlayer?.play()
  }
  • 但注意以上tap手势和pan手势会同时执行,在pan很小值得时候,tap手势也会被触发,这种情况下可以用recognizer.require(toFail:)让2个冲突的手势只能执行一个。
// TODO:
tapGestureRecognizer.require(toFail: panGestureRecognizer)

Custom UIGestureRecognizer

  • 基于UIGestureRecognizer的自定义手势,注意在Swift中,需要借助OC桥接.h文件,才能重写touches等事件方法。
  1. 新建OC-Header桥接文件,并导入头文件。
#import <UIKit/UIGestureRecognizerSubclass.h>
  1. 新建类,实现touchesBegan、moved、ended、canceled等方法。

"挠痒痒"自定义手势

class TickleGestureRecognizer: UIGestureRecognizer {
    enum Direction: String {
        case unknown = "DirectionUnknown", 
        left = "DirectionLeft", 
        right = "DirectionRight"
    }
    var requiredTickles = 2
    var distanceForTickleGesture: CGFloat = 25
    
    var tickleCount = 0
    var lastDirection: Direction = .unknown
    var curTickleStart: CGPoint = .zero
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
        guard let touch = touches.first else {
            return
        }
        curTickleStart = touch.location(in: view)
    }
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
        guard let touch = touches.first else {
            return
        }
        let ticklePoint = touch.location(in: view)
        let moveAmt = ticklePoint.x - curTickleStart.x 
        var curDirection: Direction = .unknown
        if moveAmt < 0 {
            curDirection = .left
        }
        else{
            curDirection = .right
        }
        if fabs(moveAmt) < distanceForTickleGesture {
            return
        }
        
        if (lastDirection == .left && curDirection == .right) ||
            (lastDirection == .right && curDirection == .left) || 
            lastDirection == .unknown{
            tickleCount += 1
            curTickleStart = ticklePoint
            lastDirection = curDirection
            
            if state == .possible && tickleCount > requiredTickles{
                print("He He He...")
                state = .ended
            }
        }
        
        print("\(curDirection.rawValue)")
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
        reset()
    }
    
    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent) {
        reset()
    }
    
    override func reset() {
        curTickleStart = .zero
        lastDirection = .unknown
        tickleCount = 0
        if state == .possible {
            state = .failed
        }
    }
}
  1. 使用自定义手势
let tickleGestureRecognizer = TickleGestureRecognizer(target: self, action: #selector(handleTickle(recognizer:)))
subview.addGestureRecognizer(tickleGestureRecognizer)

@objc func handleTickle(recognizer: TickleGestureRecognizer) {
    hehePlayer?.play()
}
也可以在storyboard上使用自定义手势

UILongPressGestureRecognizer

长按手势

UIScreenEdgePanGestureRecognizer

屏幕边缘滑动手势

UISwipeGestureRecognizer

扫除手势

  • 支持单点和多点手势,设置numberOfTouchesRequired属性。
  • 判断方向通过direction属性,主要有up、down、left、right
  • 可以通过recognizer.location进行子view的translation变换。

Demo Side Panel Nav Gesture

extension ContainerViewController: UIGestureRecognizerDelegate {
  @objc func handleTapGesture(_ recognizer: UIPanGestureRecognizer) {
    if currentState == .leftPanelExpanded {
      animateLeftPanel(shouldExpand: false)
    }
    else if currentState == .rightPanelExpanded {
      animateRightPanel(shouldExpand: false)
    }
  }
  
  @objc func handlePanGesture(_ recognizer: UIPanGestureRecognizer) {
    let gestureIsDraggingFromLeftToRight = (recognizer.velocity(in: view).x > 0)

    switch recognizer.state {
    case .began:
      if currentState == .bothCollapsed {
        if gestureIsDraggingFromLeftToRight {
          addLeftPanelViewController()
        } else {
          addRightPanelViewController()
        }
        
        showShadowForCenterViewController(true)
      }
      
    case .changed:
      if let rview = recognizer.view {
        rview.center.x = rview.center.x + recognizer.translation(in: view).x
        recognizer.setTranslation(CGPoint.zero, in: view)
      }
      
    case .ended:
      let velocity = recognizer.velocity(in: recognizer.view)
      if let _ = leftViewController,
        let rview = recognizer.view {
        // animate the side panel open or closed based on whether the view
        // has moved more or less than halfway
        let hasMovedGreaterThanHalfway = rview.center.x > view.bounds.size.width
        if currentState == .bothCollapsed, velocity.x > 200 {
          animateLeftPanel(shouldExpand: true)
        }
        else if currentState == .leftPanelExpanded, velocity.x < -200 {
          animateLeftPanel(shouldExpand: false)
        }
        else {
          animateLeftPanel(shouldExpand: hasMovedGreaterThanHalfway)
        }
      } else if let _ = rightViewController,
        let rview = recognizer.view {
        let hasMovedGreaterThanHalfway = rview.center.x < 0
        if currentState == .bothCollapsed, velocity.x < -200 {
          animateRightPanel(shouldExpand: true)
        }
        else if currentState == .leftPanelExpanded, velocity.x > 200 {
          animateRightPanel(shouldExpand: false)
        }
        else {
          animateRightPanel(shouldExpand: hasMovedGreaterThanHalfway)
        }
      }
      
    default:
      break
    }
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,456评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,370评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,337评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,583评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,596评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,572评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,936评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,595评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,850评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,601评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,685评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,371评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,951评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,934评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,167评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,636评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,411评论 2 342

推荐阅读更多精彩内容