Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save victorchee/3827222ddc7a4265b233ecd650d833c0 to your computer and use it in GitHub Desktop.

Select an option

Save victorchee/3827222ddc7a4265b233ecd650d833c0 to your computer and use it in GitHub Desktop.
Horizontal center scroll UICollectionView layout.
import UIKit
class HorizontalCenterScrollFlowLayout: UICollectionViewFlowLayout {
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
var offsetAdjustment = CGFloat.greatestFiniteMagnitude
let horizontalCenter = proposedContentOffset.x + collectionView!.bounds.width / 2.0
let targetRect = CGRect(x: proposedContentOffset.x, y: 0, width: collectionView!.bounds.width, height: collectionView!.bounds.height)
if let attributes = super.layoutAttributesForElements(in: targetRect) {
for attribute in attributes {
let itemHorizontalCenter = attribute.center.x
if abs(itemHorizontalCenter - horizontalCenter) < abs(offsetAdjustment) {
offsetAdjustment = itemHorizontalCenter - horizontalCenter
}
}
}
return CGPoint(x: proposedContentOffset.x + offsetAdjustment, y: proposedContentOffset.y)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment