Search code examples
iosswiftuicollectionviewuinavigationbarstatusbar

Swift iOS -NavigationBar hidesBarsOnSwipe never reappears when setting CollectionView Frame under Status Bar


I have a tabBar with a programmatic CollectionView inside a NavigationController. I noticed that when swiping up the CollectionView cells would show under the status bar. To get around it when I configured the frame for the CollectionView I used view.frame.origin.y + 20 where 20 is the height of the status bar. The reason I did that is because I used view.frame.size.height - tabBarController?.tabBar.frame.size.height to prevent the cells from showing underneath the tabBar and it worked.

I also wanted to hide the navBar on swipe so in ViewDidLoad I set navigationController?.hidesBarsOnSwipe = true.

The problem is when swiping up the navBar hides on swipe and the cells no longer show underneath the statusBar but when swiping down the navBar never comes back. Why is this happening?

Code:

override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.white
        navigationItem.title = "Home"

        navigationController?.hidesBarsOnSwipe = true

        configureCollectionView()
}

func configureCollectionView(){

        let frame = CGRect(x: view.frame.origin.x,
                       y: view.frame.origin.y + 20, // here is where I add + 20 for the statusBar's height
                       width: view.frame.size.width,
                       height: view.frame.size.height - tabBarController!.tabBar.frame.size.height) // here is where I subtracted the tabBar's height (- 49)

        let layout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)

        collectionView = UICollectionView(frame: frame, collectionViewLayout: layout)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.backgroundColor = UIColor.white
        collectionView.alwaysBounceVertical = true
        collectionView.showsVerticalScrollIndicator = false
        collectionView.register(HomeCell.self, forCellWithReuseIdentifier: homeCell)
        view.addSubview(collectionView)

}

Solution

  • It was a simple fix. I followed this answer.

    override var prefersStatusBarHidden: Bool {
        return navigationController?.isNavigationBarHidden ?? false
    }
    

    And be sure you have "View controller-based status bar appearance" = "YES" in your application .plist file.