PageView using UICollectionView in iPhone X - Swift,UIPageViewController - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

2 Nov 2017

PageView using UICollectionView in iPhone X - Swift,UIPageViewController

In most of the apps you use pageviewcontroller. Here we will show how to create page view easily with collection view.

In this article we are going to add subviews programmatically.

PageView  Using  UICollectionView

Download complete project at the bottom of this article.
First create a new project and name it as you like and save.

Add collection View:

First we need to add collection view. We do this using constraints.

Initially open ViewController.swift, add the following property:

var collectionView : UICollectionView!

Next add the following method:

func addCollectionView() {
    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
    collectionView.dataSource = self
    collectionView.delegate = self
    collectionView.backgroundColor = UIColor.white
    
    self.view.addSubview(collectionView)
    
    collectionView.translatesAutoresizingMaskIntoConstraints = false
    
    collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0.0).isActive = true
    collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0.0).isActive = true
    collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0.0).isActive = true
    collectionView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0.0).isActive = true
}

In above method we added collection view as subview to the main view using constraints.

Add cellId property as follow:

let cellId = "Cell"

Next add the following lines of code in viewDidLoad() method:

addCollectionView()
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)

Then add the delegates methods as follow:

extension ViewController: UICollectionViewDelegateFlowLayout,UICollectionViewDelegate,UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageNames.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath as IndexPath) as! CustomCollectionViewCell
        cell.backgroundColor = UIColor.red
        return cell
    }
}

Now build and run we see normal collection view as follow:

UICollectionView in Swift

Create Custom Collection Cell:

Create new file and name it as "CustomCollectionViewCell". This must be subclass UICollectionViewCell .

Open CustomCollectionViewCell.swift file and add the following code:

let imageView : UIImageView = {
    let imageView = UIImageView()
    imageView.contentMode = .scaleAspectFill
    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.clipsToBounds = true
    return imageView
}()

override init(frame: CGRect) {
    super.init(frame: frame)
    
    addSubview(imageView)
    imageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 0.0).isActive = true
    imageView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0.0).isActive = true
    imageView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0.0).isActive = true
    imageView.topAnchor.constraint(equalTo: topAnchor, constant: 0.0).isActive = true
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

Next replace the following line in viewDidLoad() method:

collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)

With

collectionView.register(CustomCollectionViewCell.self, forCellWithReuseIdentifier: cellId)

Then add the following code in addCollectionView() right after the layout creation:

layout.scrollDirection = .horizontal
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0

Add some images to project and add the image names as array:

let imageNames = ["Image1", "Image2", "Image3", "Image4"]

Next add the following delegate method inside extension as follow:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: view.frame.width, height: view.frame.height)
}

Finally add paging enabled to collection view. Add the following line inside addCollectionView() method:

collectionView.isPagingEnabled = true

Now build and run we see page View as follow:

PageView using UICollectionView

Looking good! But page control is missing.....

Adding Page Control:

For adding page control first add property as follow:

let pageControl = UIPageControl()

Next add the following two methods:

func addPageControl() {
    self.view.addSubview(pageControl)
    
    pageControl.translatesAutoresizingMaskIntoConstraints = false
    
    pageControl.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0.0).isActive = true
    pageControl.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0.0).isActive = true
    pageControl.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0.0).isActive = true
    pageControl.heightAnchor.constraint(equalToConstant: 50).isActive = true
    
    pageControl.backgroundColor = UIColor.clear
    pageControl.numberOfPages = imageNames.count
    pageControl.currentPage = 0
    pageControl.pageIndicatorTintColor = UIColor.red
}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    pageControl.currentPage = Int(scrollView.contentOffset.x) / Int(scrollView.frame.width)
}

Call addPageControl() method in viewDidLoad() method after addCollectionView() method:

Now Run the project, finally we see actual page view with page control.

PageView using UICollectionView in Swift - UIPageViewController

Download sample project with example :

No comments:

Post a Comment

Post Top Ad