Show only 7 uicollectionview cells - ios

I have a UIcollectionview that allows scrolling the content horizontally only. Each UIcollectionviewCell is a custom view showing two labels one below the other. I have set constraints in the custom cell to position these labels. Irrespective of the screen width, I always want to show 7 UICollection cells. Is this possible?

You need to change itemSize by calculating from device width
let itemSpacing: CGFloat = 5
let itemsInOneLine: CGFloat = 7
let flow = self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout
flow.sectionInset = UIEdgeInsets(top: itemSpacing, left: itemSpacing, bottom: itemSpacing, right: itemSpacing)
flow.minimumInteritemSpacing = itemSpacing
flow.minimumLineSpacing = itemSpacing
let cellWidth = (UIScreen.main.bounds.width - (itemSpacing * 2) - ((itemsInOneLine - 1) * itemSpacing)) / itemsInOneLine
flow.itemSize = CGSize(width: cellWidth, height: 120)

Hope this is What you want,
Here is the code for this.
//
// ViewController.swift
// AssignmentSO
//
// Created by Anuradh Caldera on 4/24/19.
// Copyright © 2019 personal. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
private var mycollectionview: UICollectionView!
private let cellidentifier = "cellIdentifier"
private let minimuminterspace: CGFloat = 2
override func viewDidLoad() {
super.viewDidLoad()
setCollectionView()
}
}
extension ViewController {
fileprivate func setCollectionView() {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = minimuminterspace
layout.minimumInteritemSpacing = minimuminterspace
mycollectionview = UICollectionView(frame: .zero, collectionViewLayout: layout)
mycollectionview.translatesAutoresizingMaskIntoConstraints = false
mycollectionview.register(MyCell.self, forCellWithReuseIdentifier: cellidentifier)
mycollectionview.dataSource = self
mycollectionview.delegate = self
mycollectionview.backgroundColor = .white
mycollectionview.isPagingEnabled = true
// mycollectionview.contentInset = UIEdgeInsets(top: 0, left: minimuminterspace, bottom: 0, right: minimuminterspace)
view.addSubview(mycollectionview)
let collectionviewConstraints = [mycollectionview.leftAnchor.constraint(equalTo: view.leftAnchor, constant: minimuminterspace),
mycollectionview.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
mycollectionview.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -minimuminterspace),
mycollectionview.heightAnchor.constraint(equalToConstant: UIScreen.main.bounds.height/4)]
NSLayoutConstraint.activate(collectionviewConstraints)
}
}
extension ViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 100
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellidentifier, for: indexPath) as! MyCell
cell.index = indexPath.item
cell.backgroundColor = .purple
return cell
}
}
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cellwidth = mycollectionview.frame.width/7 - minimuminterspace
let cellheight = mycollectionview.frame.height
return CGSize(width: cellwidth, height: cellheight)
}
}
class MyCell: UICollectionViewCell {
private var mainlabel: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
setLabel()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var index: Int! {
didSet {
mainlabel.text = "\(index+1)"
}
}
}
extension MyCell {
fileprivate func setLabel() {
mainlabel = UILabel()
mainlabel.translatesAutoresizingMaskIntoConstraints = false
mainlabel.textColor = .white
mainlabel.textAlignment = .center
addSubview(mainlabel)
let mainlabelConstraints = [mainlabel.centerXAnchor.constraint(equalTo: centerXAnchor),
mainlabel.centerYAnchor.constraint(equalTo: centerYAnchor)]
NSLayoutConstraint.activate(mainlabelConstraints)
}
}
Note: if you want to show 7 cells, then it is better to enable pagination. you can change the height as your need. hope this will help to someone. cheers!

Step 1 - Implement UICollectionViewDelegateFlowLayout delegate
Step 2 - Add below method
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: (collectionViewSize/7) , height: 50 )
}
Step 3 - pass size according to your requirement

Implement the collectionView layout delegate.
And divide the screen width in 7 parts as below.
please note following code is with respect to the collectionView width, considering the auto layout of collectionView width is set to screen margin.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.bounds.width/7, height:collectionView.bounds.height)
}
Though this will suffice your need, you will also need to handle the Cell's subviews to fit in the cell and display the content properly.

Related

How to stop and center horizontal CollectionView Swift

I have a collection view that scrolls horizontally, but I cannot figure out how to make the cells center and stop at the center of each scroll. So for example if you swift left the next cell should be centered in the middle of the screen, how can I do this? I'll post the collection view I have created:
class TakesViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
private lazy var selectionFeedbackGenerator = UISelectionFeedbackGenerator()
private let cellId = "TakeCell"
var currentActiveIndex: Int = 0
func setUpCollectionView(){
self.collectionView.isPrefetchingEnabled = true
self.collectionView.translatesAutoresizingMaskIntoConstraints = false
self.collectionView.backgroundColor = .clear
self.collectionView.showsHorizontalScrollIndicator = false
self.collectionView.showsVerticalScrollIndicator = false
self.collectionView.contentInset = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)
self.collectionView.alwaysBounceVertical = false
self.collectionView.alwaysBounceHorizontal = false
self.collectionView.decelerationRate = .fast
self.collectionView.configureForPeekingDelegate()
self.collectionView.register(UINib(nibName: "TakesCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "TakeCell")
}
init() {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = .horizontal
flowLayout.minimumLineSpacing = 15
super.init(collectionViewLayout: flowLayout)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
setUpCollectionView()
}
}
extension TakesViewController {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 12
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cellId, for: indexPath) as? TakeCollectionViewCell else {return UICollectionViewCell()}
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 320, height: 575)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
//Where elements_count is the count of all your items in that
//Collection view...
let cellCount = CGFloat(12)
//If the cell count is zero, there is no point in calculating anything.
if cellCount > 0 {
let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
let cellWidth = flowLayout.itemSize.width + flowLayout.minimumInteritemSpacing
//20.00 was just extra spacing I wanted to add to my cell.
let totalCellWidth = cellWidth*cellCount + 20.00 * (cellCount-1)
let contentWidth = collectionView.frame.size.width - collectionView.contentInset.left - collectionView.contentInset.right
if (totalCellWidth < contentWidth) {
//If the number of cells that exists take up less room than the
//collection view width... then there is an actual point to centering them.
//Calculate the right amount of padding to center the cells.
let padding = (contentWidth - totalCellWidth) / 2.0
return UIEdgeInsets(top: 0, left: padding, bottom: 0, right: padding)
} else {
//Pretty much if the number of cells that exist take up
//more room than the actual collectionView width, there is no
// point in trying to center them. So we leave the default behavior.
return UIEdgeInsets(top: 0, left: 40, bottom: 0, right: 40)
}
}
return UIEdgeInsets.zero
}
}
It's a scroll view. Where it stops when the user lets go is up to you.
https://developer.apple.com/documentation/uikit/uiscrollviewdelegate/1619385-scrollviewwillenddragging

How can use UIView on top of collectionView, so that when i scroll cells, UIView should not move?

I am creating horizontal carousel using collectionView Cells and I want to apply one custom view which has label on it on top of the collectionView, so that when i scroll cells the UIView should remain but changing the text of the label and cells should change. Please help me..
Hope This is What you are expecting.
Did everything programmatically for demo purpose. this is how CollectionViewController and the whole code looks like.
//
// SliderController.swift
// AssignmentSO
//
// Created by Chanaka Caldera on 7/5/19.
// Copyright © 2019 StackOverflow. All rights reserved.
//
import UIKit
private let reuseIdentifier = "Cell"
class SliderController: UICollectionViewController {
var topview: UIView!
var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
//MARK: - set up top view and label
topview = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 100))
topview.backgroundColor = .green
view.addSubview(topview)
label = UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 100))
label.text = "Title 0.0"
label.textAlignment = .center
label.font = UIFont.systemFont(ofSize: 40)
topview.addSubview(label)
// MARK: - Registering the cell and set EdgeInsets (if you are using storyboard set EdgeInset would be enough
self.collectionView!.register(CustomCell.self, forCellWithReuseIdentifier: reuseIdentifier)
self.collectionView.contentInset = UIEdgeInsets(top: 100, left: 0, bottom: 0, right: 0)
self.collectionView.isPagingEnabled = true
}
}
// MARK: Datasource
extension SliderController {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return 5
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CustomCell
cell.label.text = "Cell \(indexPath.row)"
return cell
}
}
extension SliderController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let height = UIScreen.main.bounds.height - 100
let width = UIScreen.main.bounds.width
return CGSize(width: width, height: height)
}
}
extension SliderController {
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
let xvalue = scrollView.contentOffset.x
let width = UIScreen.main.bounds.width
let cellIndex = xvalue/width
switch cellIndex {
case 0:
label.text = "Title \(cellIndex)"
case 1:
label.text = "Title \(cellIndex)"
case 2:
label.text = "Title \(cellIndex)"
case 3:
label.text = "Title \(cellIndex)"
case 4:
label.text = "Title \(cellIndex)"
default:
label.text = ""
}
}
}
//MARK: Custom cell
class CustomCell: UICollectionViewCell {
var label: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .lightGray
label = UILabel(frame: CGRect(x: 0, y: 0, width: contentView.bounds.size.width, height: contentView.bounds.size.height))
label.font = UIFont.systemFont(ofSize: 40)
label.text = "2"
label.textAlignment = .center
addSubview(label)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
hope this will help to someone and did every thing on same file for demo purpose. sorry for that. cheers!
You can load UIView() in collectionView section header like below.
Create Header Xib with class type UICollectionReusableView
Register Xib that you just created
collectionFeatured.register(TodaySectionHeader.nib, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "TodaySectionHeader")
CollectionView Delegate and DataSource
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: collectionView.bounds.width, height: 80)
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let sectionHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "TodaySectionHeader", for: indexPath) as! TodaySectionHeader
sectionHeader.labelDate.text = Date().toString(format: "EEEE dd MMMM").uppercased()
sectionHeader.labelTitle.text = "Today"
return sectionHeader
}
If you want to stick that header on top now you have to set UICollectionViewFlowLayout during collection initialization where you set delegate datasource and register xib basically in viewDidLoad
let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout // casting is required because UICollectionViewLayout doesn't offer header pin. Its feature of UICollectionViewFlowLayout
layout?.sectionHeadersPinToVisibleBounds = true

Auto sizing collection view cell size ignores auto layout on first display

Situlation
I made a horizontal scrolling collection view with UICollectionViewFlowLayout.automaticSize.
The collection view has height of 40
The cell has height of 40 which I set by autolayou on init.
Problem
The problem is that ONLY cells displayed on first displaying the collection view
has size of 50x50 which overridden autolayout height of 40 I manually set by code.
I checked the size on willDisplayCell delegate method.
When I scroll the collection view to display other cells, each newly displayed
cells have proper size with heigh of 40.
Although the cells with 50x50 size(as logged) are being displayed correctly(with height 40 it seems) on the screen.
From this, I get error messaged(logged) when I run the app on simulator and
the app crashed on if I run on my real device(iPhone8 iOS 11).
Code
ViewController
import UIKit
class HorizontalTabNavigationViewController: UIViewController {
// MARK: - Collection View
private lazy var navigationCollectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.translatesAutoresizingMaskIntoConstraints = false
cv.backgroundColor = .white
cv.dataSource = self
cv.delegate = self
return cv
}()
private typealias Cell = HorizontalTabNavigationCell
private let cellId: String = "cell"
// MARK: - Property
var items: [HorizontalTabNavigationItem] = []
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.view.translatesAutoresizingMaskIntoConstraints = false
navigationCollectionView.register(Cell.self, forCellWithReuseIdentifier: cellId)
navigationCollectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
setupSubviews()
}
private func setupSubviews() {
view.addSubview( navigationCollectionView )
[
navigationCollectionView.topAnchor .constraint(equalTo: view.topAnchor),
navigationCollectionView.leftAnchor .constraint(equalTo: view.leftAnchor),
navigationCollectionView.rightAnchor .constraint(equalTo: view.rightAnchor),
navigationCollectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
].forEach { $0.isActive = true }
}
}
extension HorizontalTabNavigationViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! Cell
//cell.setProperties(item: items[indexPath.row])
//print("Cell for item: \(items[indexPath.row].title)")
return cell
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
print("Cell Size on willDispaly cell")
print(cell.bounds.size)
print("\n")
}
}
extension HorizontalTabNavigationViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 5 // Defines horizontal spacing between cells
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return .zero
}
}
Cell
class HorizontalTabNavigationCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
setupSelfHeight()
self.backgroundColor = .orange
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupSelfHeight() {
self.heightAnchor.constraint(equalToConstant: 40).isActive = true
self.widthAnchor.constraint(equalToConstant: 120).isActive = true
}
}
I solved the problem by setting custom size to flowlayout.
Inspired by Manav's anwer on this question below.
the behavior of the UICollectionViewFlowLayout is not defined, because the cell width is greater than collectionView width
private lazy var navigationCollectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
// [Here is the answer]
// Set Height equal or less than the height of the collection view.
// This is applied on first display of cells and
// will also not affect cells auto sizing.
layout.estimatedItemSize = CGSize(width: 200, height: 40) // UICollectionViewFlowLayoutAutomaticSize
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.translatesAutoresizingMaskIntoConstraints = false
cv.showsHorizontalScrollIndicator = false
cv.backgroundColor = .white
cv.dataSource = self
cv.delegate = self
return cv
}()

Why is only image in first cell updated while the rest of the cells in uicollectionview not updated. ios swift

I'm trying to get 3 icons on the top bar.
import UIKit
class SectionHeader: UICollectionReusableView {
private let telButtonCellId = "TelButtonCell"
private let searchBarCellId = "SearchBarCell"
private let notificationButtonCellId = "NotificationButtonCell"
// MARK: - Properties
#IBOutlet weak var collectionView: UICollectionView!
// MARK: - Initialization
override func awakeFromNib() {
super.awakeFromNib()
self.collectionView.register(UINib(nibName:notificationButtonCellId, bundle: nil), forCellWithReuseIdentifier: notificationButtonCellId)
self.collectionView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width*0.2) // this is need to set the size of the collection view
self.collectionView.delegate = self
self.collectionView.dataSource = self
}
extension SectionHeader : UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: notificationButtonCellId, for: indexPath) as! NotificationButtonCell
var image = UIImage(named: "globe")
cell.imageView.image=image?.addImagePaddingShift(x: 20 , y: 20,shiftX: 0, shiftY: 10)
cell.imageView.contentMode = .scaleAspectFit
cell.imageView.bounds=cell.bounds
cell.imageView.center = cell.center;
cell.backgroundColor = UIColor.lightGray
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let frameWidth = UIScreen.main.bounds.width
let frameHeight = UIScreen.main.bounds.width*0.2
return CGSize(width: frameWidth*0.15, height: frameHeight*1.0)
}
So only the first cell will have the globe displayed.
the rest of the 2 cells are empty even though i can change the background colour.
The SectionHeader is a nib
The imageView is subview of the cell, that needs to be with its size as I see. So it needs its frame (its position in relation to its superview coordinate system - the cell) to be set to the height and width of the cell with origin (0,0). The bounds of the cell provide these dimensions so the answer can be
cell.imageView.frame = cell.bounds
or better
cell.imageView.frame = CGRect(x: 0, y: 0, width: cell.frame.width, height: cell.frame.height)

UICollectionView Goes Wrong When Scroll Down

I'm facing strange issue. My UICollectionView display half side colums if I scrolling to down.
At first they show perfectly like this
But when I scrolling down, the UICollectionView behave strange and look like this :
Below is my code to populate data to layout (dummy) :
let layoutProduct: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layoutProduct.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
layoutProduct.scrollDirection = .vertical
collectionViewProduk = UICollectionView(frame: self.view.frame, collectionViewLayout: layoutProduct)
collectionViewProduk.dataSource = self
collectionViewProduk.delegate = self
collectionViewProduk.register(ProdukPopulerCell.self, forCellWithReuseIdentifier: "ProductCell")
collectionViewProduk.backgroundColor = UIColor(red: 231/255.0, green: 231/255.0, blue: 231/255.0, alpha: 1.0)
self.view.addSubview(collectionViewProduk)
How many data to show :
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == self.collectionViewByFilter {
return 4
} else if collectionView == self.collectionViewProduk {
return 8
}
return section
}
How I populate dummy data to cell :
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == self.collectionViewProduk {
if let cellA = collectionViewProduk.dequeueReusableCell(withReuseIdentifier: "ProductCell", for: indexPath) as? ProdukPopulerCell {
cellB.backgroundColor = UIColor.white
if indexPath.row < 8 {
cellB.nameLabel.text = "Product"
cellB.theImageView.image = UIImage(named: "biometric")
cellB.priceLabel.text = "Rp 30.000"
}
return cellB
}
}
return UICollectionViewCell()
}
How I layouting the cell and make them look 2 cell in 1 rows :
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if collectionView == self.collectionViewProduk {
let collectionViewSize = collectionViewProduk.frame.size.width - 10
return CGSize(width: collectionViewSize / 2, height: collectionViewSize / 2)
}
return CGSize()
}
Can you guys spot the mistake that I make?
Create a customCollectionViewFlowLayout and apply it to your collectionview
import UIKit
class customCollectionViewFlowLayout: UICollectionViewFlowLayout {
override init() {
super.init()
setupLayout()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupLayout()
}
func setupLayout() {
minimumInteritemSpacing = 1
minimumLineSpacing = 1
scrollDirection = .vertical
}
override var itemSize: CGSize {
set {
}
get {
let numberOfColumns: CGFloat = 2
let itemWidth = (self.collectionView!.frame.width - (numberOfColumns - 1)) / numberOfColumns
return CGSize(width:itemWidth, height:itemWidth)
}
}
}
then apply it to your collectionview
yourCollectionView.collectionViewLayout = customCollectionViewFlowLayout()

Resources