How do I hide/show tabBar when tapped using Swift in iOS8

后端 未结 10 913
终归单人心
终归单人心 2020-12-04 12:44

I am trying to mimic the UINavigationController\'s new hidesBarsOnTap with a tab bar. I have seen many answers to this that either point to setting the hi

相关标签:
10条回答
  • 2020-12-04 13:17

    Swift 3 version:

    func setTabBarVisible(visible:Bool, animated:Bool) {
    
        //* This cannot be called before viewDidLayoutSubviews(), because the frame is not set before this time
    
        // bail if the current state matches the desired state
        if (tabBarIsVisible() == visible) { return }
    
        // get a frame calculation ready
        let frame = self.tabBarController?.tabBar.frame
        let height = frame?.size.height
        let offsetY = (visible ? -height! : height)
    
        // zero duration means no animation
        let duration:TimeInterval = (animated ? 0.3 : 0.0)
    
        //  animate the tabBar
        if frame != nil {
            UIView.animate(withDuration: duration) {
    
                self.tabBarController?.tabBar.frame = (self.tabBarController?.tabBar.frame.offsetBy(dx: 0, dy: offsetY!))!
                return
            }
        }
    }
    
    func tabBarIsVisible() ->Bool {
        return (self.tabBarController?.tabBar.frame.origin.y)! < self.view.frame.midY
    }
    
    0 讨论(0)
  • 2020-12-04 13:21

    Code is okay but when you use presentViewController, tabBarIsVisible() is not working. To keep UITabBarController always hidden use just this part:

    extension UITabBarController {
        func setTabBarVisible(visible:Bool, animated:Bool) {
            let frame = self.tabBar.frame
            let height = frame.size.height
            let offsetY = (visible ? -height : height)
            UIView.animateWithDuration(animated ? 0.3 : 0.0) {
                self.tabBar.frame = CGRectOffset(frame, 0, offsetY)
                self.view.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height + offsetY)
                self.view.setNeedsDisplay()
                self.view.layoutIfNeeded()
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-04 13:21

    To make the animations work with self.tabBarController?.tabBar.hidden = true just do this:

    UIView.animateWithDuration(0.2, animations: {
        self.tabBarController?.tabBar.hidden = true
    })
    

    Other than the other solution this will also work nicely with autolayout.

    0 讨论(0)
  • 2020-12-04 13:23

    You can just add this line to ViewDidLoad() in swift :

    self.tabBarController?.tabBar.hidden = true
    
    0 讨论(0)
提交回复
热议问题