Search code examples
iosswiftuitableviewuinavigationbarsubview

SubView Added to UITableView Below Navigation Bar Incorrect Y Value


I have a UITableViewController that's embedded in a UINavigationController embedded in a UITabBarController.

I am attempting to add a sub view to block out the area between the nav bar and tab bar when a condition isn't met, yet the sub view i add isn't quite in the correct place. It seems to be shifted up about the height of the status bar and nav bar combined (notice the gap below the shaded area...that should be shaded as well).

enter image description here

Here's how I'm trying to accomplish it:

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    setupLinks()
    addBlockViewIfRequired()
  }
  
  override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)
    blockView.removeFromSuperview()
  }
  override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    setSizeOfBlockView()
  }
  
  func addBlockViewIfRequired() {
    if dataModel.getAccounts().isEmpty {
      if let navController = self.navigationController {
        blockView.backgroundColor = UIColor.blackColor()
        blockView.alpha = 0.5
        setSizeOfBlockView()
        navController.view.insertSubview(blockView, belowSubview: navController.navigationBar)
      }
    }
  }
  
  func setSizeOfBlockView() {
    let blockViewRect = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)
    blockView.frame = blockViewRect
  }

Any ideas as to what I would need to adjust to make this sub view be correctly placed? Thank you!


Solution

  • I'm guessing your view is partially under your navigationBar. You can use the UI debugger to double check.

    You will need to set the blockViewRect.origin.y to the bottom of your navBar e.g.

    let blockViewRect = CGRectMake(0, navigationController?.navigationBar.frame.maxY, self.view.bounds.size.width, self.view.bounds.size.height)
    

    And just to pretty things up a bit...

    var blockViewRect = self.view.bounds
    blockViewRect.origin.y = navigationController?.navigationBar.frame.maxY
    

    FYI, the correct navigationController may be in one of your VC's parentViewControllers.