Skip to content

15.4_自定义手势识别逻辑

自定义手势识别逻辑,让你能够创建出独一无二、高度定制化的交互体验!🎉 摆脱系统自带手势的限制,打造更符合你应用场景的手势操作。

为什么要自定义手势?

系统提供的 UIGestureRecognizer 已经很强大了,但有时你可能需要:

  • 识别更复杂的手势模式,例如特定的滑动轨迹或多指组合操作。
  • 根据应用状态或用户行为动态调整手势识别的灵敏度或触发条件。
  • 与其他手势识别器进行更精细的协调和冲突处理。

自定义手势识别器能让你完全掌控手势识别的整个过程,实现更灵活、更强大的交互设计。💪

如何创建自定义手势识别器?

  1. 创建 UIGestureRecognizer 的子类:这是自定义手势识别器的基础。你需要继承 UIGestureRecognizer 并重写相关方法。

  2. 重写 touchesBegan(_:with:)touchesMoved(_:with:)touchesEnded(_:with:)touchesCancelled(_:with:) 方法:这些方法是手势识别的核心。你可以在这些方法中获取触摸事件的信息,并根据你的自定义逻辑来判断手势是否被识别。

  3. 设置 state 属性state 属性表示手势识别器的状态。你需要根据手势识别的进度来更新 state 属性。常用的状态包括:

    • .possible:手势识别器正在等待识别。
    • .began:手势识别器已经开始识别。
    • .changed:手势识别器正在识别过程中。
    • .ended:手势识别器已经识别完成。
    • .cancelled:手势识别器被取消。
    • .failed:手势识别器识别失败。
  4. 定义自定义属性和方法:你可以根据你的需要添加自定义属性和方法,例如手势识别的阈值、方向等。

示例:自定义滑动方向识别器

假设我们要创建一个只能识别水平滑动手势的识别器。

swift
class HorizontalSwipeGestureRecognizer: UIGestureRecognizer {
    private var startPoint: CGPoint = .zero
    var directionThreshold: CGFloat = 10 // 水平方向的最小滑动距离

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        if let touch = touches.first {
            startPoint = touch.location(in: view)
            state = .possible
        }
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesMoved(touches, with: event)
        guard let touch = touches.first else {
            state = .failed
            return
        }

        let currentPoint = touch.location(in: view)
        let deltaX = currentPoint.x - startPoint.x

        if abs(deltaX) > directionThreshold {
            state = .began // 或者 .changed,取决于你的需求
        } else {
            state = .failed
        }
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesEnded(touches, with: event)
        state = .ended
    }

    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesCancelled(touches, with: event)
        state = .cancelled
    }
}

在这个例子中,我们:

  • 记录了触摸开始时的位置 startPoint
  • touchesMoved 方法中计算水平方向的滑动距离 deltaX
  • 如果 deltaX 大于阈值 directionThreshold,则认为手势被识别。
  • 根据触摸事件的结束或取消,设置 state 属性为 .ended.cancelled

使用自定义手势识别器

使用自定义手势识别器与使用系统提供的手势识别器类似:

  1. 创建自定义手势识别器的实例。
  2. 将手势识别器添加到视图中。
  3. 实现手势识别器的 target-action 方法。
swift
let swipeGesture = HorizontalSwipeGestureRecognizer(target: self, action: #selector(handleSwipe(_:)))
view.addGestureRecognizer(swipeGesture)

@objc func handleSwipe(_ sender: HorizontalSwipeGestureRecognizer) {
    if sender.state == .ended {
        // 处理水平滑动手势
        print("水平滑动 detected!")
    }
}

通过自定义手势识别逻辑,你可以创造出更具创意和个性化的用户体验。 🚀 记住,实践是最好的老师!多尝试、多实验,你一定能掌握自定义手势识别的精髓。

本站使用 VitePress 制作