简体   繁体   中英

UICollectionView with pagination. Keeping the second cell in center of the screen

I am new to iOS.

I am having my collection view inside tableview cell. There are 3 cells in collection view cell.

I need to show the second cell of collection view in center of the screen as shown in the image and also want to add pagination into it. Any help will be appreciated. Image Thank You

I had to do a similar collection view a few months ago, This is the code that I use:

func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        let layout = theNameOfYourCollectionView.collectionViewLayout as! UICollectionViewFlowLayout 
        let cellWidthIncludingSpacing = layout.itemSize.width + layout.minimumLineSpacing // Calculate cell size
        let offset = scrollView.contentOffset.x
        let index = (offset + scrollView.contentInset.left) / cellWidthIncludingSpacing // Calculate the cell need to be center

        if velocity.x > 0 { // Scroll to -->
            targetContentOffset.pointee = CGPoint(x: ceil(index) * cellWidthIncludingSpacing - scrollView.contentInset.right, y: -scrollView.contentInset.top)
        } else if velocity.x < 0 { // Scroll to <---
            targetContentOffset.pointee = CGPoint(x: floor(index) * cellWidthIncludingSpacing - scrollView.contentInset.left, y: -scrollView.contentInset.top)
        } else if velocity.x == 0 { // No dragging
            targetContentOffset.pointee = CGPoint(x: round(index) * cellWidthIncludingSpacing - scrollView.contentInset.left, y: -scrollView.contentInset.top)
        }
    }

This code calculates the size of your cell, how many cells have already been shown and once the scroll is finished, adjust it to leave the cell centered.

Make sure you have the pagingEnabled of your collectionView in false if you want to use this code.

Also, implement UIScrollViewDelegate in your ViewController

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM