【发布时间】:2020-10-14 14:49:07
【问题描述】:
我希望 UI 按钮仅在按住超过设定的秒数时才响应。所以我就这样使用了 UILongPressGestureRecognizer:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var holdButton: UIButton!
@IBAction func holdButtonPressed(_ sender: Any) {
let recognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPressHappened))
recognizer.minimumPressDuration = 2.0
view.addGestureRecognizer(recognizer)
}
和处理程序
@objc func longPressHappened(gestureReconizer: UILongPressGestureRecognizer){
holdButton.backgroundColor = #colorLiteral(red: 0.7254902124, green: 0.4784313738, blue: 0.09803921729, alpha: 1)
DispatchQueue.main.async {
print ("Sucess")
}
}
如您所见,我使用了 DispatchQueue 并尝试更改按钮的颜色,但都不起作用。谁能告诉我为什么?
更新:- 我对实现答案中给出的方法感到困惑,所以我想我会再次给出我的完整代码
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var holdButton: UIButton! {
didSet {
let recognizer = UILongPressGestureRecognizer(target: self,action: #selector(longPressHappened))
recognizer.minimumPressDuration = 2.0
holdButton.addGestureRecognizer(recognizer)
}
}
override func viewDidLoad() {
super.viewDidLoad()
holdButton.layer.cornerRadius = 150
holdButton.layer.borderWidth = 1.0
holdButton.layer.borderColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
holdButton.clipsToBounds = true
}
@objc func longPressHappened(gestureReconizer: UILongPressGestureRecognizer){
holdButton.backgroundColor = #colorLiteral(red: 0.7254902124, green: 0.4784313738, blue: 0.09803921729, alpha: 1)
DispatchQueue.main.async {
print ("Sucess")
}
}
}
【问题讨论】:
-
按一下按钮,然后尝试长按,这样可以吗?
-
查看答案是否对您有用?
-
@Frankenstein 不,它没有。感谢您的尝试!