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

标签 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)

有人有解决办法吗?谢谢

最佳答案

UIGestureRecognizer 有一个名为 view 的属性,它是它附加到的 View 。 View 被声明为可选的,所以你需要打开它:

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

关于swift - 在 swift 中实现手势识别器后,如何找到按钮标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26246259/

相关文章:

Xcode 7.3 : "Thread 1: EXC_BAD_ACCESS(code=1, adress=0x0)"

ios - 如何向 UIButton 添加观察者?

ios - 未始终为 UIPageControl 触发 UIControlEventValueChanged 事件

ios - UIDatePicker 错误?达到最小内部后 UIControlEventValueChanged

ios - 是否可以从 touchesBegan 或 touchesMoved 中取消触摸?

ios - 如何在 Swift 中将 UILongPressGestureRecognizer 与 UICollectionViewCell 一起使用?

swift - 在 Swift 中,Int {get set} 类型和 Int 类型有什么区别?

swift - 编译器说我不符合 UICollectionViewDelegate;与实际使用冲突

swift - 应用程序在后台获取的 Collectionview 的 reloadData() 处崩溃

iphone - 无法使用 UILongTouchGestureRecognizer 从 MKMapView 获取坐标