View on Top of UITabBar

后端 未结 7 1869
慢半拍i
慢半拍i 2021-02-02 16:03

Similar to what the Spotify or Apple Music app does when a song is playing, it places a custom view on top of the UITabBar:

Solutions I\'ve tried:

  1. UITa

7条回答
  •  野性不改
    2021-02-02 16:44

    I got it!

    In essence, I increased the size of the original UITabBar to accomodate a custom view (and to shrink the frame of the viewcontrollers above), and then adds a duplicate UITabBar + custom view right on top of it.

    Here's the meat of what I had to do. I uploaded a functioning example of it and can be found in this repo:

    class TabBarViewController: UITabBarController {
    
        var currentlyPlaying: CurrentlyPlayingView!
        static let maxHeight = 100
        static let minHeight = 49
        static var tabbarHeight = maxHeight
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            currentlyPlaying = CurrentlyPlayingView(copyFrom: tabBar)
            currentlyPlaying.tabBar.delegate = self
    
            view.addSubview(currentlyPlaying)
            tabBar.isHidden = true
        }
        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
    
            currentlyPlaying.tabBar.items = tabBar.items
            currentlyPlaying.tabBar.selectedItem = tabBar.selectedItem
        }
        func hideCurrentlyPlaying() {
            TabBarViewController.tabbarHeight = TabBarViewController.minHeight
            UIView.animate(withDuration: 0.5, animations: {
                self.currentlyPlaying.hideCustomView()
                self.updateSelectedViewControllerLayout()
            })
        }
        func updateSelectedViewControllerLayout() {
            tabBar.sizeToFit()
            tabBar.sizeToFit()
            currentlyPlaying.sizeToFit()
            view.setNeedsLayout()
            view.layoutIfNeeded()
            viewControllers?[self.selectedIndex].view.setNeedsLayout()
            viewControllers?[self.selectedIndex].view.layoutIfNeeded()
        }
    }
    
    extension UITabBar {
    
        open override func sizeThatFits(_ size: CGSize) -> CGSize {
            var sizeThatFits = super.sizeThatFits(size)
            sizeThatFits.height = CGFloat(TabBarViewController.tabbarHeight)
            return sizeThatFits
        }
    }
    

提交回复
热议问题