Custom TabBar layout for UITabBarViewController

2019-03-01 18:18发布

问题:

Please refer to this Answer.

I am trying to do the same thing, however I want to do this in a Tab Bar App where the Now Playing bar is above the Tab Bar in all the scenes of the app.

Update:

I want to have a view at the bottom of the screen (above the tab bar) and under the content views of the different tabs (not above them). In addition, I want to have the ability to remove this view at a certain point making the main view take the whole screen.

I can do this using the mentioned Answer by changing the constraints of the nowPlaying view programmatically.

回答1:

Using UITabBarViewController subclass it is possible:

Ex:

class DashBoardViewController: UITabBarController {

    let nowPlayingBar:UIView = {
        let view = UIView(frame: .zero)
        view.backgroundColor = .blue
        return view
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        initView()
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        nowPlayingBar.frame = tabBar.frame
    }

    override func viewDidAppear(_ animated: Bool) {
        var newSafeArea = UIEdgeInsets()

        // Adjust the safe area to accommodate
        //  the height of the bottom views.
        newSafeArea.bottom += nowPlayingBar.bounds.size.height

        // Adjust the safe area insets of the
        //  embedded child view controller.
        self.childViewControllers.forEach({$0.additionalSafeAreaInsets = newSafeArea})
    }

    private func initView() {
        nowPlayingBar.frame = tabBar.frame
        view.addSubview(nowPlayingBar)
    }
}


回答2:

You'll add your view/container to your app window, you'd do something like

guard let window = (UIApplication.shared.delegate as? AppDelegate)?.window 
     else { return } // check if there's a window 

    let containerHeight: CGFloat = 50  // height for the view where you wish to add the music player 

   let containerFrame = CGRect(x:0, y: window.frame.maxY - (tabBar.frame.height + containerHeight), width: window.frame.width, height: containerHeight)
   // most important part here is the y axis in some sense, you will add the height of the tabBar and the container, then subtract it from window.frame.maxY  

   let container = UIView(frame: containerFrame)
   // now you have the container do whatever you want with it 
   window.addSubView(container) // finally add the container to window as a subview