create a collection view with pages in swift

To create a collection view with pages, follow these steps:

  1. Add a UICollectionView and set its pagingEnabled property to true.
  2. Create a custom UICollectionViewLayout subclass that will determine the position and size of each cell.
  3. Implement the UICollectionViewDataSource and UICollectionViewDelegate methods to populate the collection view with your data and handle user interactions.
  4. Add a UIPageControl to indicate the current page.
  5. Update the page control's currentPage property in the UIScrollViewDelegate method scrollViewDidEndDecelerating(_:) to reflect the current page.

Here is an example implementation:

main.swift
class CustomLayout: UICollectionViewFlowLayout {
    override func prepare() {
        super.prepare()
        scrollDirection = .horizontal
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        itemSize = collectionView!.frame.size
    }
}

class MyViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate {
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var pageControl: UIPageControl!
    
    var data = [/* your data */]

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.collectionViewLayout = CustomLayout()
        pageControl.numberOfPages = data.count
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as! MyCell
        let dataList = data[indexPath.row]
        /* configure the cell */
        return cell
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let pageNumber = Int(scrollView.contentOffset.x / scrollView.frame.size.width)
        pageControl.currentPage = pageNumber
    }
}
1570 chars
45 lines

gistlibby LogSnag