Search code examples
iosswiftuiviewviewuinavigationcontroller

UIViewController hidden behind UINavigationController but should be placed below


I'm working on a app where I've got a NavigationBar at the top and added a UIViewController as an RootViewController.

Now my plan was to add a new Subview to this UIViewController. The new Subview extended also of UIViewController. I added de view (Gray Rect) of the controller to the UIViewController but it is placed behind the NavigationBar. I don't want that.. So I searched for a solution and found something interesting..: When I just add a UIView() (Green Rect) to the UIViewController, the placing of the view works perfectly, as I would love see it from the other UIViewController-View. enter image description here My code looks like following:

class DashboardController: UIViewController {

var ccview:ContactCircleController!

override func viewDidLoad() {
    super.viewDidLoad()
    edgesForExtendedLayout = []
    self.view.backgroundColor = .white

    let test = UIView()
    test.backgroundColor = .green
    test.frame = CGRect(x: self.view.frame.width - 200, y: 0, width: self.view.frame.width / 2, height: self.view.frame.width / 2)
    self.view.addSubview(test)
    setup()
}

func setup(){
    ccview = ContactCircleController()

    ccview.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width / 2, height: self.view.frame.width / 2)
    ccview.edgesForExtendedLayout = UIRectEdge.top
    self.view.addSubview(ccview.view)
 }}

I've already unchecked the "Extend Edges" - toggle of the navigationcontroller on the storyboard. I also added edgesForExtendedLayout = [] to the UIViewController and for the UIView it worked fine. But for the view of another UIViewController... it didn't worked.

Thank you!


Solution

  • If you use Debug View Hierarchy, you will see that your gray ccview.view is not behind the navigation bar, but rather it is not keeping the height of self.view.frame.width / 2.

    This is because the .view of a UIViewController instantiated from Storyboard has by default an .autoresizingMask = [], whereas the .view of a UIViewController instantiated without a storyboard has a default .autoresizingMask = [.flexibleWidth, .flexibleHeight].

    You can correct this by changing setup() to:

    func setup(){
        ccview = ContactCircleController()
    
        ccview.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width / 2, height: self.view.frame.width / 2)
    
        // remove this line
        //ccview.edgesForExtendedLayout = UIRectEdge.top
    
        // add this line
        ccview.view.autoresizingMask = []
    
        self.view.addSubview(ccview.view)
    }