简体   繁体   中英

Listen to LongPressGesture on UITabBarItem

I want to attach a simple long press on a single UITabBarItem. Is this possible in swift 4 ? I have tried like below but the UITabBarItem doesn't have the event members that I can implement 在此处输入图片说明 The uiTabBar is the outlet. I've seen also that I can use a UITabBarDelegate but I haven't got it to work. The longTap function's signature looks like:

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

I ended up placing a UIButton on top of the UITabBarItem I wanted to attach the UILongPressGestureRecognizer to. I prepared the button using the function below:

 //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()
    }

To attach the events, I did the following:

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;

Selector methods are shown below:

@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
    }
}

The 'TabBar' at the middle was created with the events I wanted. 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM