Reputation: 10818
I'm looking for a way to replace the native UIPageViewController
horizontal paging with a UICollectionView
.
so far i did the following:
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.itemSize = collectionView.frame.size
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 10
collectionView.setCollectionViewLayout(layout, animated: false)
collectionView.isPagingEnabled = true
collectionView.alwaysBounceVertical = false
this works fine and i get an horizontal paging effect.
Now i want to add horizontal space between the pages (like u will do with UIPageViewControllerOptionInterPageSpacingKey
on UIPageViewController
)
so far i couldn't fine a way to add the spaces without damaging the paging effect.
im looking for the same behavior as with the UIPageViewController
: the cell should fill the entire screen width, and the space between the cells should only be visible when switching a page.
Upvotes: 19
Views: 25998
Reputation: 8563
Solution one:
collectionView.isPagingEnabled = false
minimumLineSpacing
for the distance between pagestargetContentOffsetForProposedContentOffset:withScrollingVelocity:
to move the contentOffset to the closest page. You can calculate the page with simple math based on your itemSize
and minimumLineSpacing
, but it can take a little work to get it right.Solution Two:
collectionView.isPagingEnabled = true
minimumLineSpacing
for the distance between pagesminimumLineSpacing
of 10 then set the frame of the collectionView to be {0,-5, width+10, height}minimumLineSpacing
to make the first and last item appear correctly.Upvotes: 32
Reputation: 39
Heres the code written in Swift 3.1, I'm sure it's easily understanding for you:
let pageSpacing: CGFloat = 10
class ViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: view.frame.width + pageSpacing, height: view.frame.height)
layout.scrollDirection = .horizontal
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
let frame = CGRect(x: 0, y: 0, width: view.frame.width + pageSpacing, height: view.frame.height)
let collectionView = UICollectionView(frame: frame, collectionViewLayout: layout)
view.addSubview(collectionView)
}
}
class MyCell: UICollectionViewCell {
var fullScreenImageView = UIImageView()
override func layoutSubviews() {
super.layoutSubviews()
fullScreenImageView.frame = CGRect(x: 0, y: 0, width: frame.width - pageSpacing, height: frame.height)
}
}
Hope that can help you.
Upvotes: 3