View on Top of UITabBar

后端 未结 7 1784
慢半拍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:57

    Unless I've misunderstood, you could create a custom view from your UITabBarController class. You can then insert it above and constrain it to the tabBar object, which is the tabBar association with the controller.

    So from your UITabBarController class, create your custom view

    class CustomTabBarController: UITabBarController {
        var customView: UIView = {
                let bar = UIView()
                bar.backgroundColor = .white
                bar.translatesAutoresizingMaskIntoConstraints = false
                return bar
            }()
    

    In viewDidLoad() add your custom view to the UITabBarController's view object and place it above the tabBar object

    override func viewDidLoad() {
            super.viewDidLoad()
    
            ...
    
            self.view.insertSubview(customView, aboveSubview: tabBar)
    

    Then after your custom view is added as a subView, add constraints so it's positioned correctly. This should also be done in viewDidLoad() but only after your view is inserted.

    self.view.addConstraints([
                NSLayoutConstraint(item: customView, attribute: .leading, relatedBy: .equal, toItem: tabBar, attribute: .leading, multiplier: 1, constant: 0),
                NSLayoutConstraint(item: customView, attribute: .trailing, relatedBy: .equal, toItem: tabBar, attribute: .trailing, multiplier: 1, constant: 0),
                NSLayoutConstraint(item: customView, attribute: .top, relatedBy: .equal, toItem: tabBar, attribute: .top, multiplier: 1, constant: -50),
                NSLayoutConstraint(item: customView, attribute: .bottom, relatedBy: .equal, toItem: tabBar, attribute: .top, multiplier: 1, constant: 0)
                ])
    

    There's a bunch of creative ways you can setup constraints to do what you want, but the constraints above should attach a view above your tabBar with a height of 50.

提交回复
热议问题