识别同一 UIButton 上的 UILongPressGestureRecognizer 和 UIPanGestureRecognizer
Posted
技术标签:
【中文标题】识别同一 UIButton 上的 UILongPressGestureRecognizer 和 UIPanGestureRecognizer【英文标题】:Recognize both UILongPressGestureRecognizer and UIPanGestureRecognizer on same UIButton 【发布时间】:2020-02-05 04:38:00 【问题描述】:我想做一个UIButton
,当你长按它时,它会开始录制视频,如果你垂直向上平移手指(同时仍然长按),视频会放大。
在我的按钮上,我添加了一个 UILongPressGestureRecognizer
和一个 UIPanGestureRecognizer
,它就是这样做的。单独地,他们工作。但是,它们不能一起工作。
如何让我的按钮在长按时进行记录,同时还允许我平移我的手指并使其也被识别?这就是我添加识别器的方式:
let long = UILongPressGestureRecognizer(target: self, action: #selector(record(gesture:)))
button.addGestureRecognizer(long)
let pan = UIPanGestureRecognizer(target: self, action: #selector(zoom(pan:)))
button.addGestureRecognizer(pan)
【问题讨论】:
你可以使用shouldRecognizeSimultaneouslyWith
这个方法
【参考方案1】:
您需要确认这两个手势的委托。 例如:
let long = UILongPressGestureRecognizer(target: self, action: #selector(record(gesture:)))
long.delegate = self
button.addGestureRecognizer(long)
let pan = UIPanGestureRecognizer(target: self, action: #selector(zoom(pan:)))
pan.delegate = self
button.addGestureRecognizer(pan)
并且有一个委托方法可以同时识别多个手势。
gestureRecognizer(_:shouldRecognizeSimultaneouslyWith:)
在你的类中定义它并返回 true。
你会得到你想要的。
【讨论】:
【参考方案2】:我知道这不是问题所要问的,但您实际上可以绕过必须使用 gestureRecognizer(_:shouldRecognizeSimultaneouslyWith:)
并使用 UILongPressGestureRecognizer
作为 UIPanGestureRecognizer
使用 UIGestureRecognizer.State
更改。这就是我过去所做的,清理事情并且比拥有两个手势识别器更合乎逻辑
【讨论】:
以上是关于识别同一 UIButton 上的 UILongPressGestureRecognizer 和 UIPanGestureRecognizer的主要内容,如果未能解决你的问题,请参考以下文章