1

I am trying to make my collection view cell to cover the height of the screen without going under the navigation bar. I have got the height of the nav bar and use it to make the height of the cell. The problem is that the cell is still taller than it should be and if I scroll down it will go under the nav bar. I needed to be exactly the height of the screen without the nav bar. Code listing below:

 override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let navBarHeight: CGFloat = (self.navigationController?.navigationBar.frame.height)!
    let heightOfCell: CGFloat = view.frame.height - navBarHeight
    return CGSize(width: view.frame.width, height: heightOfCell)

}
mihai mimi
  • 133
  • 1
  • 12
  • Do you have a tab bar at the bottom? – JoakimE Jun 02 '17 at 15:14
  • no tab bar at the bottom – mihai mimi Jun 02 '17 at 15:17
  • If the origin of the collection View is at 0.0, you should move it at the bottom of the Navigation Bar. CollectionView.frame.origin.y = (height of nav bar). That way the cells for the collection view will start just underneath the nav bar. Or set uiedgeinset for the collection view where top would be height of the nav bar – JoakimE Jun 02 '17 at 15:19
  • check this post https://stackoverflow.com/questions/43023384/uicollectionview-remove-top-padding/43025517#43025517 – Joe Jun 02 '17 at 21:21

2 Answers2

0

try next piece of code in your viewController:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    collectionView.collectionViewLayout.invalidateLayout()
}
Maksym Musiienko
  • 1,248
  • 8
  • 16
0

UIViewController has a method called scrollViewDidChangeAdjustedContentInset which has been available since ios 11 so you need to implement this method inside your ViewController to make your UIcollectioViewCell full size minus the navigationBar height.

  //inside your ViewController
   func scrollViewDidChangeAdjustedContentInset(_ scrollView: UIScrollView) {
    if #available(iOS 11.0, *) {
        scrollView.contentInsetAdjustmentBehavior = .never
    } else {
        automaticallyAdjustsScrollViewInsets = false
    }
}

 //make a cell with fullscreen size 
   func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
       
        return CGSize(width: collectionView.frame.width, height: collectionView.frame.height)
    }

Also, make sure you position the CollectionView at the bottom of NavigationBar.