Search code examples
iosswiftconstraintsuitabbarcontrolleruitabbar

How do I add constraints to my tabBarController?


I have added a tabBarController and hooked it up to viewControllers and given the tabBarController its own class. It works, but I would like to customize it by changing the constraints so that it's not right at the bottom. From what I can see there's no way to add constraints in auto layout as it's all grayed out. I gave a shot at adding it programmatically, but nothing happens.

final class TabBarViewController: UITabBarController {

    @IBOutlet var customTabBar: UITabBar!
    override func viewDidLoad() {
        self.selectedIndex = 2
        let fontAttributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 20.0)]

        UITabBarItem.appearance().setTitleTextAttributes(fontAttributes, for: .normal)

        //This doesn't work
        customTabBar.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true

        //Neither does this
        self.tabBar.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true

        //Or this
        if let tabC = self.tabBarController {
            tabC.tabBar.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
        }
    }

So how do I do this? I want the tabBar to be about 50p from the bottom.


Solution

  • You can create a container view controller to hold you UITabBarController. Then, when you set the constraints on your container view, you can add 'padding' to the bottom, to have it go upwards. Below are two screenshots explaining the layout.

    enter image description here enter image description here