gpt4 book ai didi

ios - UILongPressGestureRecognizer 不做任何事情

转载 作者:行者123 更新时间:2023-12-01 16:11:50 30 4
gpt4 key购买 nike

我想让一个 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")
}

}

}

最佳答案

您只需要使用 UIView 创建自定义按钮。向该 View 添加长按手势,并在需要的时间触发委托(delegate)/闭包。

func addLongPressGesture() {
let recognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(_:)))
recognizer.minimumPressDuration = 3.0 // Duration
customButton.addGestureRecognizer(recognizer)
}

@objc
func handleLongPress(_ gestureRecognizer: UILongPressGestureRecognizer) {
if gestureRecognizer.state == .began {
// Perform your functionality here
}
}

关于ios - UILongPressGestureRecognizer 不做任何事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62553439/

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