Search code examples
iosswiftuitableviewuiviewstatusbar

iOS 13 remove UIView for simulate status bar background


I'm working with a UITableViewController which when scrolling makes the navigationBar disappear. Now when the navigation bar is hidden when the user swipes the table view the contents of the cells are seen below the status bar ...

To solve this problem I tried to insert a UIView to simulate a background of the status bar and everything works but the problem is that when I close the UITableViewController the background view of the status bar is not removed from the superview

For now my code is this, can you help me understand where I am wrong? why can't I remove the UIView from the superview?

 override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        setupStatusBarView()

    }

    override func viewWillDisappear(_ animated: Bool) {
       super.viewWillDisappear(animated)

       navigationController?.navigationBar.isHidden = true
        UIApplication.shared.windows.first?.viewWithTag(1)?.removeFromSuperview()
   }


    //MARK: - Setup Status Bar View

    func setupStatusBarView() {

        let height = view.window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0

        let statusBarView = UIView()

        statusBarView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height:height+5)
        statusBarView.backgroundColor = .systemBackground
        statusBarView.tag = 1
        UIApplication.shared.windows.first?.addSubview(statusBarView)
    }

Solution

  • viewDidLayoutSubviews get calls multiple times and you have put setupStatusBarView() in viewDidLayoutSubviews that means your background view has been added multiple times and this is totally wrong flow!

    You are removing topmost view only not previous ones!

    You should set frame in viewDidLayoutSubviews and should add the view from viewDidLoad!