在 UITabBarItem 上监听 LongPressGesture

Listen to LongPressGesture on UITabBarItem

我想在单个 UITabBarItem 上附加一个简单的 long press。这在 swift 4 中可能吗?我试过如下但 UITabBarItem 没有我可以实现的事件成员 uiTabBar 是出口。我还看到我可以使用 UITabBarDelegate 但我还没有让它工作。 longTap 函数的签名如下所示:

@objc func longTap(_ sender: UIGestureRecognizer){}

我最终在 UITabBarItem 上放置了一个 UIButton,我想将 UILongPressGestureRecognizer 附加到。我使用以下函数准备了按钮:

 //Declare the button 
 let uiTabBar = UIButton(frame: CGRect.zero)

func setupMiddleButton() {
        // Create image
        let africaIcon = UIImage(named: "ic_africa")

        let numberOfItems = CGFloat(tabBar.items!.count)
        let tabBarItemSize = CGSize(width: tabBar.frame.width / numberOfItems, height: tabBar.frame.height)
        uiTabBar.frame = CGRect(x: 0, y: 0, width: tabBarItemSize.width, height: tabBar.frame.size.height)
        var menuButtonFrame = uiTabBar.frame
        menuButtonFrame.origin.y = self.view.bounds.height - menuButtonFrame.height - self.view.safeAreaInsets.bottom
        menuButtonFrame.origin.x = self.view.bounds.width/2 - menuButtonFrame.size.width/2
        uiTabBar.frame = menuButtonFrame
        uiTabBar.setImage(africaIcon, for: UIControlState.normal)
        //uiTabBar.backgroundColor = UIColor.green
        self.view.addSubview(uiTabBar)
        self.view.layoutIfNeeded()
    }

为了附加事件,我执行了以下操作:

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(normalTap(_:)))
                tapGesture.numberOfTapsRequired = 1
                uiTabBar.addGestureRecognizer(tapGesture)
                let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(longTap(_:)))
                uiTabBar.addGestureRecognizer(longGesture)
                //Set default tab
                self.selectedIndex = 1;

选择器方法如下:

@objc func normalTap(_ sender: UIGestureRecognizer){
    self.selectedIndex = 1;
}

@objc func longTap(_ sender: UIGestureRecognizer){
    print("Long tap")
    if sender.state == .ended {
        print("UIGestureRecognizerStateEnded")
        //Do Whatever You want on End of Gesture
        //This is when the long event is triggered
    }
    else if sender.state == .began {
        print("UIGestureRecognizerStateBegan.")
        //Do Whatever You want on Began of Gesture
    }
}

中间的'TabBar'是我想要的事件创建的。