如何使用Swift创建UIBarButton来调用UITapGestureRecognizer函数?

时间:2019-02-08 15:07:02

标签: ios swift uibarbuttonitem uitapgesturerecognizer

我的情况是,我尝试实施UIBarButton点击以在两个functions下面进行调用。下面的代码已经适用于view tab and pan,但是现在我更改按钮单击以调用以下两个功能。如何在code以下进行修改?

@objc
    func handleCardTap(recognzier:UITapGestureRecognizer) {
        switch recognzier.state {
        case .ended:
            animateTransitionIfNeeded(state: nextState, duration: 0.9)
        default:
            break
        }
    }

    @objc
    func handleCardPan (recognizer:UIPanGestureRecognizer) {
        switch recognizer.state {
        case .began:
            startInteractiveTransition(state: nextState, duration: 0.9)
        case .changed:
            let translation = recognizer.translation(in: self.cardViewController.handleArea)
            var fractionComplete = translation.y / cardHeight
            fractionComplete = cardVisible ? fractionComplete : -fractionComplete
            updateInteractiveTransition(fractionCompleted: fractionComplete)
        case .ended:
            continueInteractiveTransition()
        default:
            break
        }

    }

1 个答案:

答案 0 :(得分:0)

如果您需要从UIBarButtonItem调用这两个轻击手势识别器功能,最好的选择是创建一个自定义视图栏按钮项,并将手势识别器添加到该自定义视图。这样的事情会起作用:

let tapGestureView = UIView() // initialize & size this as you need
tapGestureView.addGestureRecognizer(UITapGestureRecognizer(action: #selector(handleCardTap(_:)), target: self))
tapGestureView.addGestureRecognizer(UITapGestureRecognizer(action: #selector(handleCardPan(_:)), target: self))
let barButton = UIBarButtonItem(customView: tapGestureView)

以下是UITapGestureRecognizers的一些其他资源 和UIBarButtonItems。但是,为同一视图设置2个不同的轻击手势似乎有些奇怪,而且其中一个是平移动作(至少是按名称)似乎很奇怪,但这就是您要实现的方式!