I have a controller that contains a UICollectionView called myCollection:
public lazy var myCollection : UICollectionView = {
let routine = UICollectionView(frame: CGRect.zero, collectionViewLayout: UICollectionViewFlowLayout());
let routineLayout = UICollectionViewFlowLayout()
routineLayout.scrollDirection = .horizontal
routine.collectionViewLayout = routineLayout
routine.decelerationRate = UIScrollView.DecelerationRate.fast
routine.translatesAutoresizingMaskIntoConstraints = false
routine.delegate = self
routine.dataSource = self
routine.backgroundColor = .clear
routine.register(MyCellView.self, forCellWithReuseIdentifier: cellId)
routine.isPagingEnabled = true
routine.showsHorizontalScrollIndicator = false
routine.showsVerticalScrollIndicator = false
routine.layer.cornerRadius = 20
routine.layer.masksToBounds = true
return routine
}()
I add this collectionView as a subview to my app, using these constraints:
NSLayoutConstraint.activate([
myCollection.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
myCollection.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor),
myCollection.widthAnchor.constraint(equalTo: view.safeAreaLayoutGuide.widthAnchor, multiplier: 1),
myCollection.heightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.heightAnchor, multiplier: 0.40)
])
For the sake of completeness, here is the code that shows cell size is 100% of the parent view with no spacing.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.width, height: collectionView.frame.height)
}
When I implement the scrollViewWillEndDragging function using above constraints, I get the right index printed out for the collection cell:
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let navigatedTo = Int(targetContentOffset.pointee.x) / Int(myCollection.frame.width)
}
However, when I reduce the size of myCollection, the right index is no longer printed out. For example:
view.safeAreaLayoutGuide.widthAnchor, multiplier: 0.90
I cannot figure out how to account for this horizontal compression in scrollViewWillEndDragging. The best guide I've found thus far is here : Snap to center of a cell when scrolling UICollectionView horizontally , but I am not able to connect the ideas together to account for this compression.