如何在swift中实现手势识别器后找到按钮标签?

时间:2014-10-07 22:22:35

标签: swift uigesturerecognizer uicontrolevents

当有人在按钮内滑动时,我想要执行一次操作。

我目前的代码如下:

    let recogniser = UISwipeGestureRecognizer(target: self, action: "didTapButton2:")
    recogniser.direction = .Up
    button.addGestureRecognizer(recogniser)

    func didTapButton2(sender: UIGestureRecognizer!) {

    //Here I want to be able to recognise which button this was sent from (they are all tagged)
    let button = sender. as UIButton //Gives an error

我需要使用手势识别器而不是UIControlEvents,因为我只需要触发一次事件。使用它会使事件发生火灾次数 - 只需要进行一次:

    button.addTarget(self, action: "didTapButton2:", forControlEvents: .TouchDragInside)

有没有人有解决方案?感谢

1 个答案:

答案 0 :(得分:6)

UIGestureRecognizer有一个名为view的属性,它是附加到的视图。视图被声明为可选,因此您需要打开它:

if let button = sender.view as? UIButton {
    // use button
    if button.tag == 10 {
        // handle button tagged with 10
    }
}