通过UILongPressGestureRecognizer传递uibutton标签?

时间:2018-06-02 07:39:36

标签: swift uilongpressgesturerecogni

我正在尝试使用长按按钮功能,但我不确定如何将按钮的标签传递给该功能。我有一个名为ChannelButton的按钮数组。长按按钮可以使用下面的代码。

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

但我需要它来修改它是这样的

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


    func handleLongPress(sender: UILongPressGestureRecognizer, buttontag) {
        doSomeFunction(buttontag)
}

我知道这不起作用,但我不确定该怎么做。

2 个答案:

答案 0 :(得分:1)

UIGestureRecognizer有一个view属性,它是附加到的view。在你的情况下,它将是你的按钮。用它来到你的按钮tag

func handleLongPress(sender: UILongPressGestureRecognizer) {
    guard let button = sender.view as? UIButton else { return }

    doSomeFunction(button.tag)
}

答案 1 :(得分:0)

您正在尝试将EXTRA参数(int)添加到IBAction选择器。你不能这样做。 IBActions有3个选择器之一:

@IBAction func actionNoParams() {
}

@IBAction func actionWSender(_ sender: Any) {
}

@IBAction func actionWSenderAndEvent(_ sender: Any, forEvent event: UIEvent) {
}

一种解决方案是查找长按手势的位置,然后检查该位置的按钮。

func handleLongPress(sender: UILongPressGestureRecognizer) {

    if sender.state == UIGestureRecognizerState.began {

        let location = sender.location(in: self.view)

        for button in ChannelButton {

            if button.frame.contains(location) {

                //This is the button that is pressed
                //Do stuff
            }
        }
    }
}

请记住符合UIGestureRecognizerDelegate