Search code examples
iosswiftuiviewaddsubview

Placing UIView To Cover TabBar & NavBar


I am trying to make a popup (UIView) with a transparent background (another UIView). Everything is working fine for the 'popup UIView' but I couldn't figure out how to bring 'transparent background UIView' (above NavigationBar and TabBar).

First I created the UIView in the Storyboard and connected the outlet:

popupView.center = CGPointMake(CGRectGetMidX(self.view.bounds), tableView.center.y);
self.view.addSubview(popupView)
popupView.clipsToBounds = true
popupView.alpha = 0

Then, while displaying popupView I am creating the transparent background UIView:

 func clicked() {
    self.popupView.alpha = 1

    let screenSize: CGRect = UIScreen.mainScreen().bounds
    let opaqueView = UIView()
    opaqueView.frame.size = CGSize(width: screenSize.width, height: screenSize.height)
    opaqueView.backgroundColor = UIColor.blackColor()
    opaqueView.alpha = 0.5

    self.view.addSubview(opaqueView)
 }

However, the background view doesn't get over NavigationBar or TabBar. I tried this but nothing changes:

myTabBar.view.bringSubviewToFront(opaqueView)

What I want to achieve is that, while having popup UIView at the very front, having opaque UIView over everything including NavBar and TabBar, but behind popup UIView


Update:

Regarding @Alex's answer, with this chunk, I achieved displaying opaqueView over TabBar & NavBar; but now it's also going above the popupView.

func display() {
   popupView.center = CGPointMake(CGRectGetMidX(self.view.bounds), tableView.center.y);
    self.view.addSubview(popupView)
    popupView.clipsToBounds = true

    let opaqueView = UIView()
    let screenSize: CGRect = UIScreen.mainScreen().bounds
    opaqueView.frame.size = CGSize(width: screenSize.width, height: screenSize.height)
    UIApplication.sharedApplication().keyWindow!.insertSubview(opaqueView, belowSubview: popupView) 
}

How can I place opaqueView below popupView while opaqueView is above everything else?


Solution

  • Try this:

    UIApplication.sharedApplication().keyWindow!.bringSubviewToFront(opaqueView)
    

    Updating for Swift 4.2

     UIApplication.shared.keyWindow!.bringSubview(toFront: opaqueView!)
    

    Updating for Swift 5

    UIApplication.shared.keyWindow!.bringSubviewToFront(opaqueView!)