0

我有 20 多个按钮,我想为所有人定义一个 UILongPressGestureRecognizer,这可能吗?

到目前为止,这不起作用:

let longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleLongGesture))

B_BTN_1.addGestureRecognizer(longPressGestureRecognizer)
B_BTN_2.addGestureRecognizer(longPressGestureRecognizer)

出于某种原因,longPressGestureRecognizer 仅适用于“B_BTN_2”。

但是通过为每个声明一个手势识别器,它可以工作:

let longPressGestureRecognizer1 = UILongPressGestureRecognizer(target: self, action: #selector(handleLongGesture))
let longPressGestureRecognizer2 = UILongPressGestureRecognizer(target: self, action: #selector(handleLongGesture))

B_BTN_1.addGestureRecognizer(longPressGestureRecognizer1)
B_BTN_2.addGestureRecognizer(longPressGestureRecognizer2)

编辑:

如果您要使用@Andre 的解决方案,并且有很多按钮,请改用它来防止索引错误(就像永远一样):

var buttons:[UIButton] = []
    buttons.append(B_BTN_1)
    buttons.append(B_BTN_2)
    buttons.append(B_BTN_3)
    .....
4

2 回答 2

2

正如@Andriy Savran 已经说过的那样,手势识别器只能附加一个视图。您可以使用循环使设置过程更简单...

override func viewDidLoad() {
    super.viewDidLoad()

    let button1 = UIButton(type: .system)
    let button2 = UIButton(type: .system)
    let button3 = UIButton(type: .system)
    // ...

    let buttons = [button1, button2, button3]

    for button in buttons {
        let longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(sender:)))
        button.addGestureRecognizer(longPressGestureRecognizer)
    }

}

func handleLongPress(sender: UILongPressGestureRecognizer) {
    guard let button = sender.view else {
        fatalError("could not get the button attached to the gesturerecognizer")
    }

    // do something
}
于 2017-02-12T09:57:02.253 回答
1

引用苹果文档:

每个手势识别器都与一个视图相关联。相比之下,一个视图可以有多个手势识别器,因为一个视图可能会响应许多不同的手势。要让手势识别器识别特定视图中发生的触摸,您必须将手势识别器附加到该视图。当用户触摸该视图时,手势识别器会收到一条消息,指出在视图对象之前发生了触摸。结果,手势识别器可以代表视图响应触摸。

https://developer.apple.com/library/content/documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/GestureRecognizer_basics/GestureRecognizer_basics.html#//apple_ref/doc/uid/TP40009541-CH2-SW21

因此,您需要为每个视图初始化手势识别器,就像您所做的那样:

但是通过为每个声明一个手势识别器,它可以工作:

let longPressGestureRecognizer1 = UILongPressGestureRecognizer(target: self, action: #selector(handleLongGesture))
let longPressGestureRecognizer2 = UILongPressGestureRecognizer(target: self, action: #selector(handleLongGesture))

B_BTN_1.addGestureRecognizer(longPressGestureRecognizer1)
B_BTN_2.addGestureRecognizer(longPressGestureRecognizer2)
于 2017-02-12T09:52:25.860 回答