UICollectionView Horizontal Paging not centered

前端 未结 11 1643
感动是毒
感动是毒 2020-12-02 09:32

I have a horizontal scrolling collectionView with each cell the size of the view. When I page through the collectionView it doesn\'t page by cell. The cells aren\'t in the c

11条回答
  •  独厮守ぢ
    2020-12-02 09:41

    Swift 3 solution based on @Santos's answer, for use if if you have a regular horizontally paging collection view without a page control like Paolo was using in his Swift 3 example.

    I used this to solve an issue where a horizontally paging cell full screen cells with a custom UICollectionViewFlowLayout animator didn't finish rotating AND ended up offset so that the the edges of a full screen cell frame were increasingly horizontally off set from the collection view's bounds as you scrolled (like in the video OP shared).

     func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer) {
    
        // Ensure the scrollview is the one on the collectionView we care are working with 
        if (scrollView == self.collectionView) {
            
            // Find cell closest to the frame centre with reference from the targetContentOffset.
            let frameCenter: CGPoint = self.collectionView.center
            var targetOffsetToCenter: CGPoint = CGPoint(x: targetContentOffset.pointee.x + frameCenter.x, y: targetContentOffset.pointee.y + frameCenter.y)
            var indexPath: IndexPath? = self.collectionView.indexPathForItem(at: targetOffsetToCenter)
            
            // Check for "edge case" where the target will land right between cells and then next neighbor to prevent scrolling to index {0,0}.
            while indexPath == nil {
                targetOffsetToCenter.x += 10
                indexPath = self.collectionView.indexPathForItem(at: targetOffsetToCenter)
            }
            // safe unwrap to make sure we found a valid index path
            if let index = indexPath { 
                // Find the centre of the target cell
                if let centerCellPoint: CGPoint = collectionView.layoutAttributesForItem(at: index)?.center {
                    
                    // Calculate the desired scrollview offset with reference to desired target cell centre.
                    let desiredOffset: CGPoint = CGPoint(x: centerCellPoint.x - frameCenter.x, y: centerCellPoint.y - frameCenter.y)
                    targetContentOffset.pointee = desiredOffset
                }
            }
        }
    }
    

提交回复
热议问题