当我第一次快速点击按钮时,按钮点击不适用于 UITapGestureRecognizer
Posted
技术标签:
【中文标题】当我第一次快速点击按钮时,按钮点击不适用于 UITapGestureRecognizer【英文标题】:Button click is not working with UITapGestureRecognizer when i tapped first time on the button in swift 【发布时间】:2017-09-06 12:30:26 【问题描述】:我在按钮单击时实现了 UITapGestureRecognizer 和 UILongPressGestureRecognizer。我的问题是当我第一次点击按钮时它不起作用,但当我第二次按下按钮时它开始工作。
let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(longTap(_:)))
longGesture.minimumPressDuration = 0.5
button.addGestureRecognizer(longGesture)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(normalTap(_:)))
tapGesture.delegate = self
tapGesture.numberOfTouchesRequired = 1
tapGesture.numberOfTapsRequired = 1
button.addGestureRecognizer(tapGesture)
@objc func longTap(_ sender: UIGestureRecognizer)
print("long tap")
@objc func normalTap(_ sender: UIGestureRecognizer)
print("Normal tap")
【问题讨论】:
你有没有在 IBAction ButtonClicked 中长按这个? 您是否尝试仅添加 1 个 tapGesture 并检查是否触发了回调? 为什么你没有被尝试addTarget
替代UITapGestureRecognizer
其他使用 button.addGestureRecognizer(tapGesture) button.addGestureRecognizer(longGesture)
代替 button.addGestureRecognizer(longGesture), button.addGestureRecognizer(tapGesture)
看到这个***.com/questions/34548263/…
【参考方案1】:
试试这个
class ViewController: UIViewController, UIGestureRecognizerDelegate
@IBOutlet weak var button: UIButton!
override func viewDidLoad()
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(longTap(_:)))
longGesture.minimumPressDuration = 0.5
button.addGestureRecognizer(longGesture)
@IBAction func buttonClicked(_ sender: Any)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(normalTap(_:)))
tapGesture.delegate = self
tapGesture.numberOfTouchesRequired = 1
tapGesture.numberOfTapsRequired = 1
button.addGestureRecognizer(tapGesture)
@objc func longTap(_ sender: UIGestureRecognizer)
print("long tap")
@objc func normalTap(_ sender: UIGestureRecognizer)
print("Normal tap")
【讨论】:
讲道理兄弟。我已经将这两个手势都放在视图中加载,然后只能正常工作。感谢您提供线索.. 将这两个手势放在视图中加载功能,以便我可以投票给你的答案。以上是关于当我第一次快速点击按钮时,按钮点击不适用于 UITapGestureRecognizer的主要内容,如果未能解决你的问题,请参考以下文章
更改集合视图的 isHidden 属性不适用于搜索栏取消按钮
为啥我的 Button 样式对象仅适用于按钮内的文本,而不适用于整个按钮?
Visual Studio 2008调试:当我点击播放按钮时,它会快速闪烁