【问题标题】:Not able to add UITapGestureRecognizer and UILongPressGestureRecognizer to a UIButton无法将 UITapGestureRecognizer 和 UILongPressGestureRecognizer 添加到 UIButton
【发布时间】:2019-09-14 13:00:49
【问题描述】:
我正在使用以下代码 sn-p 添加手势识别器:
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(attachImage))
let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPress))
tapGesture.numberOfTapsRequired = 1
cell.image.addGestureRecognizer(tapGesture)
cell.image.addGestureRecognizer(longGesture)
@objc func longPress(_ btn : UIButton) {
selectedImageIndex = btn.tag
}
@objc func attachImage(_ btn : UIButton) {
selectedImageIndex = btn.tag
}
当我按下按钮时出现以下错误
无法识别的选择器发送到实例 0x2802ec000
【问题讨论】:
标签:
ios
swift
iphone
uibutton
【解决方案1】:
如果您在imageView 上添加手势,则必须启用isUserInteractionEnabled。
imageView.isUserInteractionEnabled = true
如果你在UIButton 上添加手势,那么
@IBOutlet weak var button: UIButton!
override func viewDidLoad() {
let tapGesture = UITapGestureRecognizer(target: self, #selector (tapGestureActionHandler(_:))) //Tap function will call when user tap on button
let longGesture = UILongPressGestureRecognizer(target: self, #selector(longGestureActionHandler(_:))) //Long function will call when user long press on button.
tapGesture.numberOfTapsRequired = 1
button.addGestureRecognizer(tapGesture)
button.addGestureRecognizer(longGesture)
}
@objc func tapGestureActionHandler(_ gesture: UITapGestureRecognizer) {
print("Tap happend")
}
@objc func longGestureActionHandler(_ gesture: UILongPressGestureRecognizer) {
print("Long press")
}
【解决方案2】:
如下改变函数
@objc func longPress(_ sender : UILongPressGestureRecognizer) {
if let btn = sender.view {
selectedImageIndex = btn.tag
}
}
@objc func attachImage(_ sender : UITapGestureRecognizer) {
if let btn = sender.view {
selectedImageIndex = btn.tag
}
}
并改变手势初始化如下
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(attachImage(_:)))
let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPress(_:)))