3
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

UICollectionViewでカルーセルを作る時の注意点

Posted at

UICollectionViewでカルーセル

[iOS] UICollectionView のレイアウトクラスを作成して「左右のアイテムをチラ見せするレイアウト」を実現する
https://dev.classmethod.jp/smartphone/iphone/collection-view-layout-cell-snap/

上記から引用してSwiftで書き直したものが↓。

CarouselCollectionViewFlowLayout.swift
final class CarouselCollectionViewFlowLayout: UICollectionViewFlowLayout {
    override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
        guard let collectionView = collectionView else { return .zero }
        let pageWidth = itemSize.width + minimumLineSpacing
        let currentPage = collectionView.contentOffset.x / pageWidth

        if abs(velocity.x) > 0.2 {
            let nextPage = (velocity.x > 0) ? ceil(currentPage) : floor(currentPage)
            return CGPoint(x: nextPage * pageWidth, y: proposedContentOffset.y)
        } else {
            return CGPoint(x: round(currentPage) * pageWidth, y: proposedContentOffset.y)
        }
    }
}

このCarouselCollectionViewFlowLayoutをCollectionView.layoutに渡してやれば良い。

isPagingEnabled = trueをやってはいけない

func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { ... }

collectionView.isPagingEnabled = trueを行うと、上記処理を通るものの、returnで返しているCGPointの値は無視された挙動をする。
これに何回か引っかかっている気がするので、備忘録がてら書いた。

3
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?