Search code examples
iosswiftuiviewaddsubview

Bring Subview Above Everything But Below Another UIView


I am trying to place a UIView - popupView at the top, and another UIView (opaqueView) below popupView but above anything else. PopUpView is connected with an Outlet.

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)
    opaqueView.alpha = 0.6
    UIApplication.sharedApplication().keyWindow!.insertSubview(opaqueView, belowSubview: popupView) 
}

Using this approach causes the opaqueView getting placed over everything including the popupView. Instead, I want to have popupView above opaqueView but keep opaqueView above everything else (view, TabBar, NavBar)


Solution

  • parent.insertSubview(child, belowSubview: sibling) works only when the sibling is a direct child of parent, so that child and sibling share the same parent. The current code does not work because opaqueView (the child) and popupView (the sbiling) have different parents.

    That means either ① popupView should use the keyWindow as the parent, or ② opaqueView should use self.view as parent. Since you want opaqueView be above of everything, option ① is the only solution.