UICollectionView Programmatically With Out Main.storyboard - Swift, iOS - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

5 Sep 2017

UICollectionView Programmatically With Out Main.storyboard - Swift, iOS

In this article we are going to create a sample project which explains all about UICollectionView.

In other programming languages collection view is called as grid View.

How to create UICollectionView using Swift without storyboards.

This Article Covers All Related questions  :

How to create UICollectionView using Swift without storyboards.
create uicollectionview programmatically swift 3.
uicollectionview programmatically example.
custom uicollectionviewcell programmatically swift.
programmatically create uicollectionview swift.
uicollectionview swift example.
uicollectionview custom cell example.



UICollectionView :

An object that manages an ordered collection of data items and presents them using customizable layouts.

Mainly collection view layout is used for displaying images rather than content.


Sample Project :

Firstly create a new project  open Xcode -> File -> New -> Project -> Single View App, then tap next button. Type product name as 'UICollectionViewProgramitically' then tap next and select the folder to save project.

We are not going to use Main.storyboard, so delete it and tap on 'Move to trash'.

 

Main.storyboard, so delete it and tap on 'Move to trash'.

Now if you run the project, it will crash with a reason 'Could not find a storyboard named 'Main' in bundle'. So fix that, go to project general settings and under 'Deployment Info' delete Main from 'Main Interface'.




'Main Interface'  to empty

Now run we will see black screen with out any crash. Good!


Let's get started. Open ViewController.swift them change class name from ViewController to UICollectionViewController.

Open AppDelegate.swift, add the following code inside 'didFinishLaunchingWithOptions' method.

window = UIWindow(frame: UIScreen.main.bounds) // 1
window?.makeKeyAndVisible()
let layout = UICollectionViewFlowLayout() // 2
let viewController = ViewController(collectionViewLayout: layout) // 3
window?.rootViewController = UINavigationController(rootViewController: viewController) // 4

1. Creating a window of size equal to device size. This window will keep all View Controllers hierarchy.

2. UICollectionViewFlowLayout is a default layout for collection View.


3. Initializing the ViewController with default layout.


4. Setting up the rootViewController to the window. We embedded view Controller inside UINavigationController.

Build and Run we still see the black background but here we are having navigation bar too.

Navigation bar

Creating Custom CollectionViewCell:

Firstly we will start with Custom Cell. Add the following class at the end of view controller class.
class CustomCell: UICollectionViewCell{
    
}

First we need to initialize cell. So add the following code inside CustomCell.
override init(frame: CGRect) {
    super.init(frame: frame)
}

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

In this collection view we are going to show images so, let's create imageView. Add the following code after init(frame: CGRect) method :
let imgView : UIImageView = {
    let imageView = UIImageView()
    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.image = UIImage(named: "car.png")
    imageView.contentMode = .scaleAspectFill
    return imageView
}()

Here we are showing car image, so drag the image to the project and name it as car.png.

Then add the imgView to cell and provide auto layout as we required. Add the following code inside init(frame: CGRect) method :
addSubview(imgView)
imgView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
imgView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
imgView.topAnchor.constraint(equalTo: topAnchor).isActive = true
imgView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true

Great we created custom collection view cell.

Next step is adding custom cell to collection view.

Add Custom cell to Collection View :

First create cell identifier. Add the following line before viewDidLoad() method.
let cellIdentifier = "ImageCell"

Next register collection view with custom class. Add the following code inside viewDidLoad() method:
collectionView?.backgroundColor = UIColor.white
collectionView?.register(CustomCell.self, forCellWithReuseIdentifier: cellIdentifier)

There are two delegate methods which are required

1. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int

2. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell

First one is for number of cells we need in a section.

Second one is for, which cell we are going to use. We can use different custom cells in one UICollectionView. Here we have one cell so no worries.

Add the following delegate methods : 

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 6
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! CustomCell
    
    return cell
}

Build and Run, we will see images. Great working fine but the padding between cell are not looking great.

create uicollectionview programmatically swift 3.


For that we have different delegate layout methods. We use some of them for our layout.


First add UICollectionViewDelegateFlowLayout delegate next to UICollectionViewController class.

Then add the following methods for layout and padding.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let width = view.frame.width
    return CGSize(width: (width - 15)/2, height: (width - 15)/2)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 5
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 5
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
}

Now Build and Run, we see car images with good looking.

create uicollectionview programmatically swift 3.
Download sample project with examples :

No comments:

Post a Comment

Post Top Ad