Search code examples
iosswiftuikituitabbarcontrolleruitabbar

How to change a TabBar location in iOS 14


In my app I want to be able to place a UIView under my TabBar (to use ad banner). I successfully implemented the UIView, but I can't change the TabBar location (the TabBar to be above the UIView). I try solutions for iOS 13 and early but they don't work on iOS 14. My UIView still is in the foreground over the TabBar. my

An example of how I want it to be: example

My code now:

class MainTabBarController: UITabBarController {
...
lazy var bannerAd: UIView = {
   let view = UIView()
   view.translatesAutoresizingMaskIntoConstraints = false
   view.backgroundColor = .green
   return view
}()
...
override func viewDidLoad() {
   super.viewDidLoad()
   view.addSubview(bannerAd)
   bannerAd.heightAnchor.constraint(equalToConstant: 44).isActive = true
   bannerAd.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
   bannerAd.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true
}
...
override func viewWillLayoutSubviews() {
   super.viewWillLayoutSubviews()
   self.tabBar.invalidateIntrinsicContentSize()
   var tabFrame = self.tabBar.frame
   tabFrame.size.height = tabBarHeight
   tabFrame.origin.y = tabFrame.origin.y - 44
   self.tabBar.frame = tabFrame
   }
}

Solution

  • You can try ( key is in using viewDidLayoutSubviews instead of viewWillLayoutSubviews )

    class MainTabBarController: UITabBarController {
     
        lazy var bannerAd: UIView = {
           let view = UIView()
           view.translatesAutoresizingMaskIntoConstraints = false
           view.backgroundColor = .green
           return view
        }()
         
        override func viewDidLoad() {
           super.viewDidLoad()
           view.addSubview(bannerAd)
           bannerAd.heightAnchor.constraint(equalToConstant: 44).isActive = true
           bannerAd.leadingAnchor.constraint(equalTo: view.leadingAnchor)
           bannerAd.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
           bannerAd.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true
        }
         
        override func viewDidLayoutSubviews() {
           super.viewDidLayoutSubviews()
           self.tabBar.invalidateIntrinsicContentSize()
           var tabFrame = self.tabBar.frame
           tabFrame.size.height = 44
           tabFrame.origin.y = tabFrame.origin.y - 44
           self.tabBar.frame = tabFrame
           }
    }
    

    enter image description here