gpt4 book ai didi

ios - 我如何使用 UILongPressGestureRecognizer 计算长按按钮的时间

转载 作者:行者123 更新时间:2023-11-28 05:50:31 25 4
gpt4 key购买 nike

我如何计算使用 UILongPressGestureRecognizer 按下按钮的时间;我希望在 displayLabel.text 中打印长按计数时间

我已经尝试了最可行的方法。

@IBOutlet weak var buttonPressed: UIButton!
@IBOutlet weak var displayLabel: UILabel!

var buttonPressedCount : Int = 0

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

let longPressObj = UILongPressGestureRecognizer(target: self, action: #selector(longPressButton))
longPressObj.minimumPressDuration = 2
longPressObj.numberOfTouchesRequired = 1
self.view.addGestureRecognizer(longPressObj)


// below statement is not a right one but i tried many possiblity including this one.
if longPressObj.minimumPressDuration == TimeInterval(2) {
displayLabel.text = "Longpressed for 2 seconds"
} else if longPressObj.minimumPressDuration == TimeInterval(3) {
displayLabel.text = "3"
} else if longPressObj.minimumPressDuration == TimeInterval(3) {
displayLabel.text = "4"
}


}
@IBAction func longPressButton() {

displayLabel.text = "Button pressed for \(buttonPressedCount)"
}

我想显示长按 NOT BUTTON CLICKED 的时间。

enter image description here

提前致谢!

编辑:-1.我只想在用户执行长按时显示运行持续时间。我真的很感激实时计数2. 停止按下后显示总持续时间也会有帮助。

( /image/ppr0W.png )

最佳答案

你的目标函数应该包括发送者,然后你可以得到 UILongPressGestureRecognizer 的状态。

这是 Apple official document .

首先保存手势开始时间,然后你可以使用当前时间减去开始按下时间得到状态.ended(或/和.cancelled)的持续时间>, .failed).

示例代码:

class ViewController: UIViewController {
var touchBeginTime: Double = 0
var touchCountTimer: Timer?

override func viewDidLoad() {
super.viewDidLoad()

let longPressObj = UILongPressGestureRecognizer(target: self, action: #selector(longPressButton(sender:)))
longPressObj.minimumPressDuration = 2
longPressObj.numberOfTouchesRequired = 1
self.view.addGestureRecognizer(longPressObj)
}

@IBAction func longPressButton(sender: UILongPressGestureRecognizer) {
switch sender.state {
case .began:
touchCountTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: { (timer) in
print("User pressing \(Date().timeIntervalSince1970 - self.touchBeginTime) sec.")
})
touchBeginTime = Date().timeIntervalSince1970
break;

case .changed:
//print("Long pressed changed \(Date().timeIntervalSince1970 - touchBeginTime)")
break;

case .ended, .cancelled, .failed:
touchCountTimer?.invalidate()
print("User pressed total \(Date().timeIntervalSince1970 - touchBeginTime) sec.")
break;

default:
break;
}
}
}

关于ios - 我如何使用 UILongPressGestureRecognizer 计算长按按钮的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53145571/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com