按钮cancel手势 跟 swipe上滑手势 冲突
问题
最近做需求遇到一个问题,设计想在播放器底部播控栏添加上滑手势,换起换台面板。但是因为播控栏上很多按钮,当手势起始位置为按钮内时上滑别会被识别为 UIButton 的 cancel 手势,导致无法换起面板。
搜索了一番,也没找到解决方案,最后自己各种猜测➕测试,得出一个解决方案:按钮点击事件改用 Tap 手势实现,扩展 UIView 在 touchesMoved 方法里判断手势方向是否为上滑。
实现
1、实现 touchesMoved ,并新增 touchPoint 属性记录每次 touch 位置,并跟上一次比较,y 比上一次小,就判断为上滑 2、新增 didReceiveSwipeUp 属性,回调上滑事件
代码语言:javascript复制typealias MOSwipeUpCallback = () -> ()
struct MOAssociatedKeys {
static var touchPointKey: String = "touchPoint"
static var swipeUpCallbackKey: String = "swipeUpCallback"
}
extension UIView {
public var touchPoint: CGPoint? {
get {
return objc_getAssociatedObject(self, &MOAssociatedKeys.touchPointKey) as? CGPoint
}
set {
objc_setAssociatedObject(self, &MOAssociatedKeys.touchPointKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
var didReceiveSwipeUp: MOSwipeUpCallback? {
get {
return objc_getAssociatedObject(self, &MOAssociatedKeys.swipeUpCallbackKey) as? MOSwipeUpCallback
}
set {
objc_setAssociatedObject(self, &MOAssociatedKeys.swipeUpCallbackKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
open override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
guard let touch = touches.first else { return }
let point = touch.location(in: self)
if let touchPoint = self.touchPoint {
if (touchPoint.y > point.y) {
print("swipe up")
guard let callback = self.didReceiveSwipeUp else { return }
callback();
}
} else {
self.touchPoint = point
}
}
}
使用
1、view 和 button 都可响应上滑手势
代码语言:javascript复制// MARK: - 解决:上滑手势 跟 按钮 cancel 手势 冲突
func swipeGestureTest() {
let view = UIView(frame: self.view.bounds)
view.backgroundColor = UIColor(white: 1, alpha: 0.5)
view.isUserInteractionEnabled = true
view.didReceiveSwipeUp = {
print("did reveive swipe up")
}
self.view.addSubview(view)
let btn = UIView(frame: .zero)
let tap = UITapGestureRecognizer(target: self, action: #selector(didClickBtn))
btn.addGestureRecognizer(tap)
btn.backgroundColor = .red
btn.didReceiveSwipeUp = {
print("did reveive swipe up btn")
}
self.view.addSubview(btn)
btn.snp.makeConstraints { make in
make.top.left.equalTo(self.view).offset(200)
make.height.width.equalTo(44.0)
}
}
@objc func didClickBtn() {
print("did clic button")
}
Demo:swipeGestureTest() 方法