也许,使用 UILongPressGestureRecognizer 是最普遍的解决方案。但是我遇到了两个烦人的麻烦:
- 有时,当我们移动触摸时,此识别器会以不正确的方式工作;
- 识别器会拦截其他触摸动作,因此我们无法以正确的方式使用 UICollectionView 的高亮回调。
让我建议一个有点蛮力,但按要求工作的建议:
为长按我们的单元格声明一个回调描述:
typealias OnLongClickListener = (view: OurCellView) -> Void
用变量扩展UICollectionViewCell(例如,我们可以将其命名为OurCellView):
/// To catch long click events.
private var longClickListener: OnLongClickListener?
/// To check if we are holding button pressed long enough.
var longClickTimer: NSTimer?
/// Time duration to trigger long click listener.
private let longClickTriggerDuration = 0.5
在我们的单元格类中添加两个方法:
/**
Sets optional callback to notify about long click.
- Parameter listener: A callback itself.
*/
func setOnLongClickListener(listener: OnLongClickListener) {
self.longClickListener = listener
}
/**
Getting here when long click timer finishs normally.
*/
@objc func longClickPerformed() {
self.longClickListener?(view: self)
}
并在此处覆盖触摸事件:
/// Intercepts touch began action.
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
longClickTimer = NSTimer.scheduledTimerWithTimeInterval(self.longClickTriggerDuration, target: self, selector: #selector(longClickPerformed), userInfo: nil, repeats: false)
super.touchesBegan(touches, withEvent: event)
}
/// Intercepts touch ended action.
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
longClickTimer?.invalidate()
super.touchesEnded(touches, withEvent: event)
}
/// Intercepts touch moved action.
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
longClickTimer?.invalidate()
super.touchesMoved(touches, withEvent: event)
}
/// Intercepts touch cancelled action.
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
longClickTimer?.invalidate()
super.touchesCancelled(touches, withEvent: event)
}
然后在我们集合视图的控制器中的某个地方声明回调监听器:
let longClickListener: OnLongClickListener = {view in
print("Long click was performed!")
}
最后在 cellForItemAtIndexPath 中为我们的单元格设置回调:
/// Data population.
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath)
let castedCell = cell as? OurCellView
castedCell?.setOnLongClickListener(longClickListener)
return cell
}
现在我们可以拦截单元格上的长按操作。