ios - Get time pressed in UILongPressGestureRecognizer
问题描述
I'm trying to get the time that a UIView
is pressed, using UILongPressGestureRecognizer
But, the states of press:UILongPressGestureRecognizer
are .began
, .end
, .cancelled
, .changed
.
But, I'm trying to know if has x
seconds pressed to change the control of the UIView
.
My current code is:
override func viewDidLoad() {
super.viewDidLoad()
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(NavigationViewController.displayDebugger(_:)))
self.view.addGestureRecognizer(longPressRecognizer)
}
@objc public func displayDebugger(_ press:UILongPressGestureRecognizer){
if press.state == .began{
startDate = Date()
}
else if press.state == .ended{
endDate = Date()
let components = Calendar.current.dateComponents([.second], from: startDate, to: endDate)
if(components.second! >= 1){
let debugger = LogView()
debugger.loadRequests()
}
}
}
But, I don't find the way to know the pressed time. Exist a way to do it?
解决方案
当长按开始时,记下时间(开始)。当它取消、完成或失败时;可选地计算从开始的秒数。如果按下持续时间超过 5 秒,则 myView 为红色。
class MyViewController : UIViewController {
var start: Date?
override func loadView() {
view = UIView()
view.isUserInteractionEnabled = true
view.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(tap)))
}
@objc func tap(gr: UILongPressGestureRecognizer) {
switch gr.state {
case .began:
start = Date()
case .failed, .cancelled, .ended:
guard let temp = start else { return }
let seconds = Date().timeIntervalSince(temp)
if seconds > 5 { myView.backgroundcolor = UIColor.red }
print(seconds)
default:
break
}
}
}
推荐阅读
- python - 无法在python中获取url
- python - 最大两列数据框python pandas
- excel - 动态合并多个打印区域以在 Excel 宏中保存为 pdf
- angular - Angular Stopping and Clearing an interval
- python - 如何从数据框制作字典?
- python-3.x - Leetcode 无法理解一行代码 250 解决方案
- c# - 按数组中定义的顺序对字符串列表进行排序的有效方法?
- javascript - 溢出滚动表内的绝对位置
- java - 在 PostRequest 中使用 EntityManager 时出现错误 500
- javascript - vue-dropzone 不会在文件添加时生成缩略图