Created
June 22, 2019 13:56
-
-
Save iosharry/74133ab58261dbe1df460e34215f4aae to your computer and use it in GitHub Desktop.
Collectionview Paging Center
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension ViewController: UIScrollViewDelegate { | |
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { | |
// CollectionView Item Size | |
let cellWidth = collectionViewFlowLayout.itemSize.width + collectionViewFlowLayout.minimumLineSpacing | |
var offset = targetContentOffset.pointee | |
// 이동한 x좌표 값과 item의 크기를 비교 후 페이징 값 설정 | |
let index = (offset.x + scrollView.contentInset.left) / cellWidth | |
var roundedIndex = round(index) | |
// 스크롤 방향 체크 | |
// item 절반 사이즈 만큼 스크롤로 판단하여 올림, 내림 처리 | |
if scrollView.contentOffset.x > targetContentOffset.pointee.x { | |
roundedIndex = floor(index) | |
} else { | |
roundedIndex = ceil(index) | |
} | |
// 위 코드를 통해 페이징 될 좌표 값을 targetContentOffset에 대입 | |
offset = CGPoint(x: roundedIndex * cellWidth - scrollView.contentInset.left, y: -scrollView.contentInset.top) | |
targetContentOffset.pointee = offset | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment