UIScrollView 手势冲突,子View无法获取touches事件解决方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qin_shi/article/details/80942415

问题

UIScrollView 下的子View,手势滑动中,无法获取touchesBegan等事件。

解决方式

自定义MyUIScrollView,继承自UIScrollView,复写touchesBegan等事件,在此事件中把获取的滑动事件等传递下去。

class MyUIScrollView: UIScrollView {

    var callback: TouchesCallBack?
    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
       super.init(coder: aDecoder)
    }

}
//MARK: - 手势操作
extension MyUIScrollView {

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        next?.touchesBegan(touches, with: event)
        super.touchesBegan(touches, with: event)
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        next?.touchesMoved(touches, with: event)
        super.touchesMoved(touches, with: event)
    }

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

重点就是 next?.touches 方法

问题引申

假如有一个需求:

  1. UIScrollView可以滑动
  2. UIScrollView中子View可以随手势拖动。
  3. 手势触摸到子View时, 子View要首先响应拖拽事件,UIScrollView不响应
  4. 手势触摸到非子View时,UIScrollView响应滑动事件

实际操作中发现,当手势触摸到子View时,UIScrollView马上进行了滑动,但是当触摸子View达到一定时间后,发现子View可以滑动,UIScrollView不滑动了。这种问题就是不满足需求三。
原因就是UIScrollView有一个hitTest方法,当触摸的时间小于150ms时,UIScrollView会立马响应,反之,则会把事件传递下去。

解决方式:

复写hitTest,在此方法里判断是否响应子View的拖拽操作

extension MyUIScrollView { 
    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        callback?.myHitTest(point, with: event)
        return self
    }
   }

猜你喜欢

转载自blog.csdn.net/qin_shi/article/details/80942415