ios - 如何检测“长按”
问题描述
我有一个UIView
视图,我想在用户按下它然后释放时执行一些操作。我UITapGestureRecognizer
在视图中添加了一个,它仅在点击持续时间很短时触发。如果用户触摸视图,等待几秒钟然后抬起手指,什么也不会发生。如何检测“长按”事件?
UILongPressGestureRecognizer
对我不起作用,因为当手指仍然触摸屏幕时它会触发。
解决方案
您可以通过跟踪 whentouchesBegan
和来做到这一点touchesEnded
:
class LongTapView: UIView {
var touchStart: Date!
var callback: ((Double)->())?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
touchStart = Date()
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touchPoint = touches.first?.location(in: self),
self.bounds.contains(touchPoint) else {
// touch moved outside of self,
// so don't consider it "still pressed"
touchStart = Date.distantFuture
return
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touchPoint = touches.first?.location(in: self),
self.bounds.contains(touchPoint) else {
// touch was lifted outside of self
return
}
let seconds = -(touchStart.timeIntervalSinceNow)
if seconds < 0.0 {
// this will be the case if touchesMoved outside of self
// and then was dragged back in
return
}
// tell the controller how long the view was touched
callback?(seconds)
}
}
你可以像这样使用它:
class TouchTestViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let v = LongTapView()
v.frame = CGRect(x: 80, y: 120, width: 150, height: 150)
v.backgroundColor = .red
view.addSubview(v)
v.callback = { elapsedTime in
// do what you want here, for example:
if elapsedTime > 4.0 {
print("View was pressed longer than 4 seconds!")
} else {
print("View was pressed for only \(elapsedTime) seconds")
}
}
}
}
推荐阅读
- google-apps-script - 使用多个字符串范围并将它们组合成一个数组
- html - 中心日期选择器模式
- swift - 迭代视频
- python - 使用 groupby 和 apply 时为多索引中的一个索引创建新级别
- javascript - 数组可变性和变量引用场景不清楚
- c# - asp.net core 2.2 未使用 WebApp Azure 配置中设置的 ConnectionString
- amazon-s3 - 通过 CloudFront 下载压缩的 CSV 文件
- swiftui - 测量 SwiftUI 视图的渲染大小?
- php - 使用每个 PHP 导出到 CSV
- python-3.x - 请告诉我在编写代码以从互联网下载图像时哪里出错了