how to use center vertically cells in collection view in paging mode in swift 4?

两盒软妹~` 提交于 2019-12-05 11:48:17

Regarding the SO Question you mentioned and using, that is to centre the whole section not individual cells. Some of your code might be invalid(needs to be redone).

First and most important, set the constraints of your collectionView for full screen. Remember to take safeAre/TopGuide into account, this will make sure that collection view is below the navigation bar if there is one.

This will make sure that your collectionView is up to date

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        myCollectionView.collectionViewLayout.invalidateLayout()
    }

Dump/comment below code and set insets to (0,0,0,0) in inspector of collectionView in story board. In same inspector change Min Spacing to 0 for cells and for line, both.

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {

     let navBarHeight       = self.navigationController?.navigationBar.frame.height
     let collectionViewHeight = (self.collectionView?.frame.height)! - navBarHeight!
     let itemsHeight        = self.collectionView?.contentSize.height

     let topInset = ( collectionViewHeight - itemsHeight! ) / 4

     return UIEdgeInsetsMake(topInset ,0, 0 , 0)
}

Also remove/comment below code

 showImagesCV.contentInset = UIEdgeInsets(top: spacing, left: spacing, bottom: spacing, right: spacing)
    if let flowLayout = showImagesCV.collectionViewLayout as? UICollectionViewFlowLayout{
        cellWidth = UIScreen.main.bounds.width
        cellHeight = cellWidth //yourCellHeight = cellWidth if u want square cell
        flowLayout.minimumLineSpacing = spacing
        flowLayout.minimumInteritemSpacing = spacing
        UIView.performWithoutAnimation {
        }
    }

Now change your sizeForItemAt like this.

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return collectionView.frame.size
  }

UICollectionViewCell Now in your collectionView cell, make sure that your image view is 1:1 and in centre. Also handle constraints of your other UI components.

PS : This is easy approach, other would be to write custom flowLayout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!