Ios – UITabBar with safe area inside programmatically created UIViewController

autolayoutiossafearealayoutguideswiftuitabbar

Before you mark it as duplicate please note, that I did read this and this seems to not apply to UITabBar

Both UIViewController and UITabBar are created programmatically. Constraints are set like:

public override func viewDidLoad() {
    super.viewDidLoad()
    self.view.bringSubview(toFront: self.tabBar)
}

And self.tabBar:

lazy var tabBar: UITabBar = {
    let tab = UITabBar()
    self.view.addSubview(tab)
    tab.translatesAutoresizingMaskIntoConstraints = false
    tab.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
    tab.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
    tab.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true //This line will change in second part of this post.
    return tab
}()

And this show UITabBar like this:

enter image description here

And it's too small cause it's not taking safe areas into consideration. So I did change line:

tab.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true

to:

tab.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor).isActive = true

And it's then shown like this:

enter image description here

So it's also not shown as expected. The goal here is sth like this:

enter image description here

How to make constraints to show UITabBar like this?

Best Answer

Here I did it:

let tabBar = UITabBar()

override func viewDidLoad() {
    super.viewDidLoad()
    addTabbar()
}
override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()
    addHeightConstraintToTabbar()
}

func addTabbar() -> Void {
    self.view.addSubview(tabBar)
    tabBar.translatesAutoresizingMaskIntoConstraints = false
    tabBar.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
    tabBar.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
    tabBar.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
    let item1 = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.bookmarks, tag: 1)
    let item2 = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.contacts, tag: 2)

    tabBar.items = [item1, item2]
    self.view.bringSubview(toFront: tabBar)
}

func addHeightConstraintToTabbar() -> Void {
    let heightConstant:CGFloat = self.view.safeAreaInsets.bottom + 49.0
    tabBar.heightAnchor.constraint(equalToConstant: heightConstant).isActive = true
}

Result:

enter image description here


May not know, is it correct to do in this way. You need to make it better.

Related Topic