I just started learning about UICollectionViews. I'm wondering if anyone knows how to specify the number of columns in a collectionview. The default is set to 3 (iPhone/portrait). I've looked at the documentation and can't seem to find a concise answer.
With Swift 5 and iOS 12.3, you can use one the 4 following implementations in order to set the number of items per row in your UICollectionView while managing insets and size changes (including rotation).
#1. Subclassing UICollectionViewFlowLayout and using UICollectionViewFlowLayout's itemSize property
ColumnFlowLayout.swift:
import UIKit
class ColumnFlowLayout: UICollectionViewFlowLayout {
let cellsPerRow: Int
init(cellsPerRow: Int, minimumInteritemSpacing: CGFloat = 0, minimumLineSpacing: CGFloat = 0, sectionInset: UIEdgeInsets = .zero) {
self.cellsPerRow = cellsPerRow
super.init()
self.minimumInteritemSpacing = minimumInteritemSpacing
self.minimumLineSpacing = minimumLineSpacing
self.sectionInset = sectionInset
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepare() {
super.prepare()
guard let collectionView = collectionView else { return }
let marginsAndInsets = sectionInset.left + sectionInset.right + collectionView.safeAreaInsets.left + collectionView.safeAreaInsets.right + minimumInteritemSpacing * CGFloat(cellsPerRow - 1)
let itemWidth = ((collectionView.bounds.size.width - marginsAndInsets) / CGFloat(cellsPerRow)).rounded(.down)
itemSize = CGSize(width: itemWidth, height: itemWidth)
}
override func invalidationContext(forBoundsChange newBounds: CGRect) -> UICollectionViewLayoutInvalidationContext {
let context = super.invalidationContext(forBoundsChange: newBounds) as! UICollectionViewFlowLayoutInvalidationContext
context.invalidateFlowLayoutDelegateMetrics = newBounds.size != collectionView?.bounds.size
return context
}
}
CollectionViewController.swift:
import UIKit
class CollectionViewController: UICollectionViewController {
let columnLayout = ColumnFlowLayout(
cellsPerRow: 5,
minimumInteritemSpacing: 10,
minimumLineSpacing: 10,
sectionInset: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
)
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.collectionViewLayout = columnLayout
collectionView?.contentInsetAdjustmentBehavior = .always
collectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 59
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
cell.backgroundColor = UIColor.orange
return cell
}
}
#2. Using UICollectionViewFlowLayout's itemSize method
import UIKit
class CollectionViewController: UICollectionViewController {
let margin: CGFloat = 10
let cellsPerRow = 5
override func viewDidLoad() {
super.viewDidLoad()
guard let collectionView = collectionView, let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout else { return }
flowLayout.minimumInteritemSpacing = margin
flowLayout.minimumLineSpacing = margin
flowLayout.sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin)
collectionView.contentInsetAdjustmentBehavior = .always
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
}
override func viewWillLayoutSubviews() {
guard let collectionView = collectionView, let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else { return }
let marginsAndInsets = flowLayout.sectionInset.left + flowLayout.sectionInset.right + collectionView.safeAreaInsets.left + collectionView.safeAreaInsets.right + flowLayout.minimumInteritemSpacing * CGFloat(cellsPerRow - 1)
let itemWidth = ((collectionView.bounds.size.width - marginsAndInsets) / CGFloat(cellsPerRow)).rounded(.down)
flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 59
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
cell.backgroundColor = UIColor.orange
return cell
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
collectionView?.collectionViewLayout.invalidateLayout()
super.viewWillTransition(to: size, with: coordinator)
}
}
#3. Using UICollectionViewDelegateFlowLayout's collectionView(_:layout:sizeForItemAt:) method
import UIKit
class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
let inset: CGFloat = 10
let minimumLineSpacing: CGFloat = 10
let minimumInteritemSpacing: CGFloat = 10
let cellsPerRow = 5
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.contentInsetAdjustmentBehavior = .always
collectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return minimumLineSpacing
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return minimumInteritemSpacing
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let marginsAndInsets = inset * 2 + collectionView.safeAreaInsets.left + collectionView.safeAreaInsets.right + minimumInteritemSpacing * CGFloat(cellsPerRow - 1)
let itemWidth = ((collectionView.bounds.size.width - marginsAndInsets) / CGFloat(cellsPerRow)).rounded(.down)
return CGSize(width: itemWidth, height: itemWidth)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 59
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
cell.backgroundColor = UIColor.orange
return cell
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
collectionView?.collectionViewLayout.invalidateLayout()
super.viewWillTransition(to: size, with: coordinator)
}
}
#4. Subclassing UICollectionViewFlowLayout and using UICollectionViewFlowLayout's estimatedItemSize property
CollectionViewController.swift:
import UIKit
class CollectionViewController: UICollectionViewController {
let items = [
"Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
"Lorem ipsum dolor sit amet, consectetur.",
"Lorem ipsum dolor sit amet.",
"Lorem ipsum dolor sit amet, consectetur.",
"Lorem ipsum dolor sit amet, consectetur adipiscing.",
"Lorem ipsum.",
"Lorem ipsum dolor sit amet.",
"Lorem ipsum dolor sit.",
"Lorem ipsum dolor sit amet, consectetur adipiscing.",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor.",
"Lorem ipsum dolor sit amet, consectetur."
]
let columnLayout = FlowLayout(
cellsPerRow: 3,
minimumInteritemSpacing: 10,
minimumLineSpacing: 10,
sectionInset: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
)
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.collectionViewLayout = columnLayout
collectionView?.contentInsetAdjustmentBehavior = .always
collectionView?.register(Cell.self, forCellWithReuseIdentifier: "Cell")
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! Cell
cell.label.text = items[indexPath.row]
return cell
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
collectionView?.collectionViewLayout.invalidateLayout()
super.viewWillTransition(to: size, with: coordinator)
}
}
FlowLayout.swift:
import UIKit
class FlowLayout: UICollectionViewFlowLayout {
let cellsPerRow: Int
required init(cellsPerRow: Int = 1, minimumInteritemSpacing: CGFloat = 0, minimumLineSpacing: CGFloat = 0, sectionInset: UIEdgeInsets = .zero) {
self.cellsPerRow = cellsPerRow
super.init()
self.minimumInteritemSpacing = minimumInteritemSpacing
self.minimumLineSpacing = minimumLineSpacing
self.sectionInset = sectionInset
estimatedItemSize = UICollectionViewFlowLayout.automaticSize
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
guard let layoutAttributes = super.layoutAttributesForItem(at: indexPath) else { return nil }
guard let collectionView = collectionView else { return layoutAttributes }
let marginsAndInsets = collectionView.safeAreaInsets.left + collectionView.safeAreaInsets.right + sectionInset.left + sectionInset.right + minimumInteritemSpacing * CGFloat(cellsPerRow - 1)
layoutAttributes.bounds.size.width = ((collectionView.bounds.width - marginsAndInsets) / CGFloat(cellsPerRow)).rounded(.down)
return layoutAttributes
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let superLayoutAttributes = super.layoutAttributesForElements(in: rect)!.map { $0.copy() as! UICollectionViewLayoutAttributes }
guard scrollDirection == .vertical else { return superLayoutAttributes }
let layoutAttributes = superLayoutAttributes.compactMap { layoutAttribute in
return layoutAttribute.representedElementCategory == .cell ? layoutAttributesForItem(at: layoutAttribute.indexPath) : layoutAttribute
}
// (optional) Uncomment to top align cells that are on the same line
/*
let cellAttributes = layoutAttributes.filter({ $0.representedElementCategory == .cell })
for (_, attributes) in Dictionary(grouping: cellAttributes, by: { ($0.center.y / 10).rounded(.up) * 10 }) {
guard let max = attributes.max(by: { $0.size.height < $1.size.height }) else { continue }
for attribute in attributes where attribute.size.height != max.size.height {
attribute.frame.origin.y = max.frame.origin.y
}
}
*/
// (optional) Uncomment to bottom align cells that are on the same line
/*
let cellAttributes = layoutAttributes.filter({ $0.representedElementCategory == .cell })
for (_, attributes) in Dictionary(grouping: cellAttributes, by: { ($0.center.y / 10).rounded(.up) * 10 }) {
guard let max = attributes.max(by: { $0.size.height < $1.size.height }) else { continue }
for attribute in attributes where attribute.size.height != max.size.height {
attribute.frame.origin.y += max.frame.maxY - attribute.frame.maxY
}
}
*/
return layoutAttributes
}
}
Cell.swift:
import UIKit
class Cell: UICollectionViewCell {
let label = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
label.numberOfLines = 0
backgroundColor = .orange
contentView.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
label.topAnchor.constraint(equalTo: contentView.layoutMarginsGuide.topAnchor).isActive = true
label.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor).isActive = true
label.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor).isActive = true
label.bottomAnchor.constraint(equalTo: contentView.layoutMarginsGuide.bottomAnchor).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
layoutIfNeeded()
label.preferredMaxLayoutWidth = label.bounds.size.width
layoutAttributes.bounds.size.height = contentView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
return layoutAttributes
}
// Alternative implementation
/*
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
label.preferredMaxLayoutWidth = layoutAttributes.size.width - contentView.layoutMargins.left - contentView.layoutMargins.right
layoutAttributes.bounds.size.height = contentView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
return layoutAttributes
}
*/
}
CollectionViews are very powerful, and they come at a price. Lots, and lots of options. As omz said:
there are multiple ways you could change the number of columns
I'd suggest implementing the <UICollectionViewDelegateFlowLayout> Protocol, giving you access to the following methods in which you can have greater control over the layout of your UICollectionView, without the need for subclassing it:
collectionView:layout:insetForSectionAtIndex:
collectionView:layout:minimumInteritemSpacingForSectionAtIndex:
collectionView:layout:minimumLineSpacingForSectionAtIndex:
collectionView:layout:referenceSizeForFooterInSection:
collectionView:layout:referenceSizeForHeaderInSection:
collectionView:layout:sizeForItemAtIndexPath:
Also, implementing the following method will force your UICollectionView to update it's layout on an orientation change: (say you wanted to re-size the cells for landscape and make them stretch)
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
duration:(NSTimeInterval)duration{
[self.myCollectionView.collectionViewLayout invalidateLayout];
}
Additionally, here are 2 really good tutorials on UICollectionViews:
http://www.raywenderlich.com/22324/beginning-uicollectionview-in-ios-6-part-12
http://skeuo.com/uicollectionview-custom-layout-tutorial
I implemented UICollectionViewDelegateFlowLayout on my UICollectionViewController and override the method responsible for determining the size of the Cell. I then took the screen width and divided it with my column requirement. For example, I wanted to have 3 columns on each screen size. So here's what my code looks like -
- (CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
float cellWidth = screenWidth / 3.0; //Replace the divisor with the column count requirement. Make sure to have it in float.
CGSize size = CGSizeMake(cellWidth, cellWidth);
return size;
}
Expanding on noob's answer:
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
let totalSpace = flowLayout.sectionInset.left
+ flowLayout.sectionInset.right
+ (flowLayout.minimumInteritemSpacing * CGFloat(numberOfItemsPerRow - 1))
let size = Int((collectionView.bounds.width - totalSpace) / CGFloat(numberOfItemsPerRow))
return CGSize(width: size, height: size)
}
This allows for any spacing between the cells. It assumes an Int member variable called numberOfItemsPerRow and also that all the cells are square and the same size. As noted in jhilgert00's answer we must also react to orientation changes, but now by using viewWillTransitionToSize as willRotateToInterfaceOrientation is depreciated.
Here is the working code for Swift 3 or above, to have a two-columns layout :
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
let nbCol = 2
let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
let totalSpace = flowLayout.sectionInset.left
+ flowLayout.sectionInset.right
+ (flowLayout.minimumInteritemSpacing * CGFloat(nbCol - 1))
let size = Int((collectionView.bounds.width - totalSpace) / CGFloat(nbCol))
return CGSize(width: size, height: size)
}
Feel free to change "nbCol" to your desired number of columns.
Updated to Swift 5+ iOS 13+
Collectionview Estimate Size must be none
Declare margin for cell
let margin: CGFloat = 10
In viewDidLoad configure minimumInteritemSpacing, minimumLineSpacing, sectionInset
guard let collectionView = docsColl, let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else { return }
flowLayout.minimumInteritemSpacing = margin
flowLayout.minimumLineSpacing = margin
flowLayout.sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin)
UICollectionViewDataSource method sizeForItemAt
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let noOfCellsInRow = 2 //number of column you want
let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
let totalSpace = flowLayout.sectionInset.left
+ flowLayout.sectionInset.right
+ (flowLayout.minimumInteritemSpacing * CGFloat(noOfCellsInRow - 1))
let size = Int((collectionView.bounds.width - totalSpace) / CGFloat(noOfCellsInRow))
return CGSize(width: size, height: size)
}
If you are lazy using delegate.
extension UICollectionView {
func setItemsInRow(items: Int) {
if let layout = self.collectionViewLayout as? UICollectionViewFlowLayout {
let contentInset = self.contentInset
let itemsInRow: CGFloat = CGFloat(items);
let innerSpace = layout.minimumInteritemSpacing * (itemsInRow - 1.0)
let insetSpace = contentInset.left + contentInset.right + layout.sectionInset.left + layout.sectionInset.right
let width = floor((CGRectGetWidth(frame) - insetSpace - innerSpace) / itemsInRow);
layout.itemSize = CGSizeMake(width, width)
}
}
}
PS: Should be called after rotation too
Updated to Swift 3:
Instead of the flow layout, I prefer using custom layout for specific column number and row number. Because:
It can be dragged horizontally if column number is very big.
It is more acceptable logically because of using column and row.
Normal cell and Header cell: (Add UILabel as a IBOutlet to your xib):
class CollectionViewCell: UICollectionViewCell {
#IBOutlet weak var label: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.backgroundColor = UIColor.black
label.textColor = UIColor.white
}
}
class CollectionViewHeadCell: UICollectionViewCell {
#IBOutlet weak var label: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.backgroundColor = UIColor.darkGray
label.textColor = UIColor.white
}
}
Custom layout:
let cellHeight: CGFloat = 100
let cellWidth: CGFloat = 100
class CustomCollectionViewLayout: UICollectionViewLayout {
private var numberOfColumns: Int!
private var numberOfRows: Int!
// It is two dimension array of itemAttributes
private var itemAttributes = [[UICollectionViewLayoutAttributes]]()
// It is one dimension of itemAttributes
private var cache = [UICollectionViewLayoutAttributes]()
override func prepare() {
if self.cache.isEmpty {
self.numberOfColumns = self.collectionView?.numberOfItems(inSection: 0)
self.numberOfRows = self.collectionView?.numberOfSections
// Dynamically change cellWidth if total cell width is smaller than whole bounds
/* if (self.collectionView?.bounds.size.width)!/CGFloat(self.numberOfColumns) > cellWidth {
self.cellWidth = (self.collectionView?.bounds.size.width)!/CGFloat(self.numberOfColumns)
}
*/
for row in 0..<self.numberOfRows {
var row_temp = [UICollectionViewLayoutAttributes]()
for column in 0..<self.numberOfColumns {
let indexPath = NSIndexPath(item: column, section: row)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath as IndexPath)
attributes.frame = CGRect(x: cellWidth*CGFloat(column), y: cellHeight*CGFloat(row), width: cellWidth, height: cellHeight)
row_temp.append(attributes)
self.cache.append(attributes)
}
self.itemAttributes.append(row_temp)
}
}
}
override var collectionViewContentSize: CGSize {
return CGSize(width: CGFloat(self.numberOfColumns)*cellWidth, height: CGFloat(self.numberOfRows)*cellHeight)
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var layoutAttributes = [UICollectionViewLayoutAttributes]()
for attributes in cache {
if attributes.frame.intersects(rect) {
layoutAttributes.append(attributes)
}
}
return layoutAttributes
}
}
CollectionView:
let CellIdentifier = "CellIdentifier"
let HeadCellIdentifier = "HeadCellIdentifier"
class CollectionView: UICollectionView, UICollectionViewDelegate, UICollectionViewDataSource {
init() {
let layout = CustomCollectionViewLayout()
super.init(frame: CGRect.zero, collectionViewLayout: layout)
self.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: CellIdentifier)
self.register(UINib(nibName: "CollectionViewHeadCell", bundle: nil), forCellWithReuseIdentifier: HeadCellIdentifier)
self.isDirectionalLockEnabled = true
self.dataSource = self
self.delegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func updateCollectionView() {
DispatchQueue.main.async {
self.reloadData()
}
}
// MARK: CollectionView datasource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 20
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 20
}
override func numberOfItems(inSection section: Int) -> Int {
return 20
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let column = (indexPath as NSIndexPath).row
let row = (indexPath as NSIndexPath).section
if column == 0 {
let cell : CollectionViewHeadCell = collectionView.dequeueReusableCell(withReuseIdentifier: HeadCellIdentifier, for: indexPath) as! CollectionViewHeadCell
cell.label.text = "\(row)"
return cell
}
else if row == 0 {
let cell : CollectionViewHeadCell = collectionView.dequeueReusableCell(withReuseIdentifier: HeadCellIdentifier, for: indexPath) as! CollectionViewHeadCell
cell.label.text = "\(column)"
return cell
}
else {
let cell : CollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: CellIdentifier, for: indexPath) as! CollectionViewCell
cell.label.text = String(format: "%d", arguments: [indexPath.section*indexPath.row])
return cell
}
}
// MARK: CollectionView delegate
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let column = (indexPath as NSIndexPath).row
let row = (indexPath as NSIndexPath).section
print("\(column) \(row)")
}
}
Use CollectionView from ViewController:
class ViewController: UIViewController {
let collectionView = CollectionView()
override func viewDidLoad() {
collectionView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(collectionView)
self.view.backgroundColor = UIColor.red
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[collectionView]|", options: [], metrics: nil, views: ["collectionView": collectionView]))
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[collectionView]|", options: [], metrics: nil, views: ["collectionView": collectionView]))
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
collectionView.updateCollectionView()
}
}
Finally you can have fancy CollectionView!
Because UICollectionView is so flexible, there are multiple ways you could change the number of columns, depending on the kind of layout you use.
The UICollectionViewFlowLayout (which is probably what you're working with) doesn't specify a number of columns directly (because it depends on the view size/orientation). The easiest way to change it would be to set the itemSize property and/or minimumInteritemSpacing/minimumLineSpacing.
Swift 3.0. Works for both horizontal and vertical scroll directions and variable spacing
Specify number of columns
let numberOfColumns: CGFloat = 3
Configure flowLayout to render specified numberOfColumns
if let flowLayout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
let horizontalSpacing = flowLayout.scrollDirection == .vertical ? flowLayout.minimumInteritemSpacing : flowLayout.minimumLineSpacing
let cellWidth = (collectionView.frame.width - max(0, numberOfColumns - 1)*horizontalSpacing)/numberOfColumns
flowLayout.itemSize = CGSize(width: cellWidth, height: cellWidth)
}
This answer is for swift 3.0 -->
first conform to the protocol :
UICollectionViewDelegateFlowLayout
then add these methods :
//this method is for the size of items
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = collectionView.frame.width/3
let height : CGFloat = 160.0
return CGSize(width: width, height: height)
}
//these methods are to configure the spacing between items
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(0,0,0,0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
First add UICollectionViewDelegateFlowLayout as protocol.
Then:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
var columnCount = 3
let width = (view.frame.width - 20) / columnCount
return CGSize(width: width, height: width)
}
Its all about layout you want to draw. You can create custom class inheriting from UICollectionViewFlowLayout. Currently there is not any direct method to set columns. If you want to achieve this kind of functionality you need to do it manually. You need to handle it in your custom flow layout class.
Now question will arise how you will do it? If you dont want to disturb cell frame you can adjust
collectionView:layout:minimumInteritemSpacingForSectionAtIndex:
collectionView:layout:minimumLineSpacingForSectionAtIndex:
Another way is provide you own positions of cells. By overriding below two methods, which will get called during your layout formation.
- (NSArray*)layoutAttributesForElementsInRect:(CGRect)rect
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)path
UICollectionViewLayoutAttributes is class which will deal with cell position, frame, Zindex etc
I just wanted to append to Imanou Petit's answer #2. To ensure margins are exact regardless of screen width, I use an iterative solver with a desired margin, and the # of columns as inputs. I also added a directional flag on where their final margins will be compared to their target.
The iterative solver is shown below and returns cellWidth and margin.
private func iterativeCellSpacing(targetMargins : CGFloat,
cellsPerRow : Int,
isMinTarget : Bool) -> (CGFloat, CGFloat)
{
var w : CGFloat = 0
var m : CGFloat = targetMargins
let cols : CGFloat = CGFloat(cellsPerRow)
let numMargins : CGFloat = cols + 1.0
let screenWidth : CGFloat = collectionView!.bounds.size.width
var delta = CGFloat.greatestFiniteMagnitude
while abs(delta) > 0.001
{
let totalMarginSpacing = numMargins * m
let totalCellSpacing = screenWidth - totalMarginSpacing
if (isMinTarget)
{
w = floor(totalCellSpacing / cols)
m = ceil((screenWidth - cols * w) / numMargins)
}
else
{
w = ceil(totalCellSpacing / cols)
m = floor((screenWidth - cols * w) / numMargins)
}
delta = screenWidth - w * CGFloat(cellsPerRow) - m * numMargins
}
return (w, m)
}
I call it as such:
fileprivate var margin: CGFloat = 20
fileprivate var cellWidth : CGFloat = 80
fileprivate let cellsPerRow = 4
override func viewDidLoad()
{
super.viewDidLoad()
(cellWidth, margin) = iterativeCellSpacing(targetMargins: margin, cellsPerRow: 4, isMinTarget: true)
...
}
I then apply the cellWidth and margin values to the flow layout as such:
extension MyCollectionController : UICollectionViewDelegateFlowLayout
{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
return CGSize(width: cellWidth, height: cellWidth)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
collectionView?.collectionViewLayout.invalidateLayout()
super.viewWillTransition(to: size, with: coordinator)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
{
return UIEdgeInsetsMake(margin, margin, margin, margin)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat
{
return margin
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat
{
return margin
}
}
Hope this helps. There probably is an easier way to ensure margins are exact, but this is one method. Also, this code hasn't been tested for devices that allow rotating collectionviews.
Thanks,
the perfect solution is to
Using UICollectionViewDelegateFlowLayout
but you can easily so calculate the cell width and divided on the wanted number of columns you want
the tricky is to make the width with no fraction
(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
CGFloat screenWidth = self.view.frame.size.width;
CGFloat marginWidth = (screenWidth - collectionView.frame.size.width);
CGFloat cellWith = (collectionView.frame.size.width - marginWidth )/3;
cellWith= floorf(cellWith);
CGSize retval = CGSizeMake(cellWith,cellWith);
return retval;}
I made a collection layout.
To make the separator visible, Set the background color of the collection view to gray.
One row per section.
Useage:
let layout = GridCollectionViewLayout()
layout.cellHeight = 50 // if not set, cellHeight = Collection.height/numberOfSections
layout.cellWidth = 50 // if not set, cellWidth = Collection.width/numberOfItems(inSection)
collectionView.collectionViewLayout = layout
Layout:
import UIKit
class GridCollectionViewLayout: UICollectionViewLayout {
var cellWidth : CGFloat = 0
var cellHeight : CGFloat = 0
var seperator: CGFloat = 1
private var cache = [UICollectionViewLayoutAttributes]()
override func prepare() {
guard let collectionView = self.collectionView else {
return
}
self.cache.removeAll()
let numberOfSections = collectionView.numberOfSections
if cellHeight <= 0
{
cellHeight = (collectionView.bounds.height - seperator*CGFloat(numberOfSections-1))/CGFloat(numberOfSections)
}
for section in 0..<collectionView.numberOfSections {
let numberOfItems = collectionView.numberOfItems(inSection: section)
let cellWidth2 : CGFloat
if cellWidth <= 0
{
cellWidth2 = (collectionView.bounds.width - seperator*CGFloat(numberOfItems-1))/CGFloat(numberOfItems)
}
else
{
cellWidth2 = cellWidth
}
for row in 0..<numberOfItems {
let indexPath = NSIndexPath(row: row, section: section)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath as IndexPath)
attributes.frame = CGRect(x: (cellWidth2+seperator)*CGFloat(row),
y: (cellHeight+seperator)*CGFloat(section),
width: cellWidth2,
height: cellHeight)
//row_temp.append(attributes)
self.cache.append(attributes)
}
//self.itemAttributes.append(row_temp)
}
}
override var collectionViewContentSize: CGSize {
guard let collectionView = collectionView else
{
return CGSize.zero
}
if (collectionView.numberOfSections <= 0)
{
return collectionView.bounds.size
}
let width:CGFloat
if cellWidth <= 0
{
width = collectionView.bounds.width
}
else
{
width = cellWidth*CGFloat(collectionView.numberOfItems(inSection: 0))
}
let numberOfSections = CGFloat(collectionView.numberOfSections)
var height:CGFloat = 0
height += numberOfSections * cellHeight
height += (numberOfSections - 1) * seperator
return CGSize(width: width, height: height)
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var layoutAttributes = [UICollectionViewLayoutAttributes]()
for attributes in cache {
if attributes.frame.intersects(rect) {
layoutAttributes.append(attributes)
}
}
return layoutAttributes
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return cache[indexPath.item]
}
}
Try This,It's working perfect for me,
Follow below steps:
1. Define values in .h file.
#define kNoOfColumsForCollection 3
#define kNoOfRowsForCollection 4
#define kcellSpace 5
#define kCollectionViewCellWidth (self.view.frame.size.width - kcellSpace*kNoOfColumsForCollection)/kNoOfColumsForCollection
#define kCollectionViewCellHieght (self.view.frame.size.height-40- kcellSpace*kNoOfRowsForCollection)/kNoOfRowsForCollection
OR
#define kNoOfColumsForCollection 3
#define kCollectionViewCellWidthHieght (self.view.frame.size.width - 6*kNoOfColumsForCollection)/kNoOfColumsForCollection
2.Add Code in collection View Layout data source methods as below,
#pragma mark Collection View Layout data source methods
// collection view with autolayout
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
return 4;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
return 1;
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
return UIEdgeInsetsMake(4, 4, 4, 4);
}
- (CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return
CGSizeMake(kCollectionViewCellWidth,kCollectionViewCellHieght);
// CGSizeMake (kCollectionViewCellWidthHieght,kCollectionViewCellWidthHieght);
}
Hope this will be help for some one.
Related
I am trying to implement the Tags Layout using UICollectionView.
It works fine but only at some places the word is not displayed properly (Cropped) (mostly at the end of the UICollectioView frame). I have attached the screenshot as well.
I followed this Setup a collectionView with "tag"-like cells and tried to implement the same but it didn't work for me.
class UserProfileTagsFlowLayout: UICollectionViewFlowLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let attributesForElementsInRect = super.layoutAttributesForElements(in: rect) else { return nil }
guard var newAttributesForElementsInRect = NSArray(array: attributesForElementsInRect, copyItems: true) as? [UICollectionViewLayoutAttributes] else { return nil }
var leftMargin: CGFloat = 0.0;
for attributes in attributesForElementsInRect {
if (attributes.frame.origin.x == self.sectionInset.left) {
leftMargin = self.sectionInset.left
}
else {
var newLeftAlignedFrame = attributes.frame
newLeftAlignedFrame.origin.x = leftMargin
attributes.frame = newLeftAlignedFrame
}
leftMargin += attributes.frame.size.width + 8 // Makes the space between cells
newAttributesForElementsInRect.append(attributes)
}
return newAttributesForElementsInRect
}
}
I am using the below array to populate the data :
data = ["Kishor", "iOS", "Developer", "Software Engineer", "ABCD", "Coding", "Xcode", "I am an iOS Developer","JKLMNO" , "Testing Coding", "Development", "XYZ-XYZ-XYZCD", "Enable the Tag Layout", "Layouts Arrangement"]
But if you see in the screenshot, last word of the first line "ABCD", 'D' is cropped and also few of the words are cropped at the end of the frame.
Below is my UICollectionView (Inside the UITableViewCell)
class TagListCell: UITableViewCell {
#IBOutlet weak var tagListCollection: UICollectionView!
var data: [String] = []
override func awakeFromNib() {
super.awakeFromNib()
}
fileprivate func setCollectioView() {
self.setupCollectionnViewLayout()
self.tagListCollection.register(UINib(nibName: "TagListNameCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "TagListNameCollectionViewCell")
tagListCollection.delegate = self
tagListCollection.dataSource = self
}
private func setupCollectionnViewLayout() {
let layout = UserProfileTagsFlowLayout()
//layout.estimatedItemSize = CGSize.init(width: 50, height: 50)
layout.scrollDirection = .vertical
tagListCollection.collectionViewLayout = layout
}
// MARK: UIView functions
override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
self.tagListCollection.layoutIfNeeded()
let size = tagListCollection.collectionViewLayout.collectionViewContentSize
let newSize = CGSize(width: size.width, height: size.height + 1)
debugPrint("New Size : \(newSize)")
return newSize
}
func setData(data: [String]) {
self.setCollectioView()
self.data = data
}
}
//MARK:- UICollectionView Delegate and DataSource
extension TagListCell: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TagListNameCollectionViewCell", for: indexPath) as? TagListNameCollectionViewCell {
cell.titleLable.text = data[indexPath.row]
return cell
}
else {
return UICollectionViewCell()
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let tag = data[indexPath.row]
let font = UIFont.systemFont(ofSize: 17)//UIFont(name: "Label Test Data", size: 16)!
let size = tag.size(withAttributes: [NSAttributedString.Key.font: font])
let dynamicCellWidth = size.width
return CGSize(width: dynamicCellWidth, height: 50)
}
// Space between rows
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 5
}
// Space between cells
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 5
}
}
I can't figure out how I can adjust the cell sizes without "breaking" rows count.
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
Before I use customized UICollectionViewFlowLayout, the scroll function works Fine, but when I set my layout to UICollectionView, it can't scroll anymore, but all contents display well because my layout works.
I want to make PinterestLayout, so I created my layout displayed as the following photo.
I am try to use this lay out into my Instagram-style app with UICollection header and cell
My Code for my layout is the following:
class MyLayout : UICollectionViewFlowLayout{
fileprivate let numberOfColumns = 2
weak var delegate : MyLayoutDelegate!
fileprivate var cache = [UICollectionViewLayoutAttributes]()
fileprivate var contentHeight : CGFloat = 0
fileprivate var contentWidth : CGFloat{
guard let collectionView = collectionView else {return 0.0}
let insets = collectionView.contentInset
return collectionView.bounds.width - (insets.left + insets.right)
}
override var collectionViewContentSize: CGSize{
return CGSize(width: contentWidth, height: contentHeight)
}
override init() {
super.init()
self.minimumLineSpacing = 1
self.minimumInteritemSpacing = 1
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepare() {
guard let collection = collectionView else {return}
let columnWidth = contentWidth / CGFloat(numberOfColumns)
let xOffset: [CGFloat] = [0,columnWidth]
var yOffset = [CGFloat](repeating: 190, count: numberOfColumns)
var columnToPlacePhoto = 0
for item in 0 ..< collection.numberOfItems(inSection: 0){
let indexPath = IndexPath(item: item, section: 0)
let photoHeight : CGFloat = delegate.collectionView(collection, numberOfColumns: numberOfColumns, heightForPhotoAtIndexPath: indexPath)
let frame = CGRect(x: xOffset[columnToPlacePhoto], y: yOffset[columnToPlacePhoto], width: columnWidth, height: photoHeight)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.frame = frame
self.cache.append(attributes)
yOffset[columnToPlacePhoto] = yOffset[columnToPlacePhoto] + photoHeight
columnToPlacePhoto = columnToPlacePhoto < (numberOfColumns - 1) ? (columnToPlacePhoto + 1) : 0
}
}
//
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let layoutAttributes = super.layoutAttributesForElements(in: rect)
layoutAttributes?.forEach({ (attribute) in
// I did this to keep attribute of Collection View Header, without this step, my Header doesn't show up
if attribute.representedElementKind == UICollectionView.elementKindSectionHeader{
cache.append(attribute)
}})
return cache
}
}
I assign my layout to Collection View
class ProfileVC: UICollectionViewController, UICollectionViewDelegateFlowLayout, {
override func viewDidLoad() {
super.viewDidLoad()
let layout = MyLayout()
layout.delegate = self
self.collectionView.collectionViewLayout = layout
self.collectionView.isScrollEnabled = true
}
I also set the number of items, number of sections, size of header and so on.
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return posts.count
}
// Set size of header
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: view.frame.width, height: 190)
}
// Set cell
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ProfilePostCell
cell.post = posts[indexPath.item]
return cell
}
I am pretty sure my original Collection View works well
enter image description here
But after I add the following, it can not scroll. Please help me out of here, thanks in advance.
let layout = MyLayout()
layout.delegate = self
self.collectionView.collectionViewLayout = layout
self.collectionView.isScrollEnabled = true
I have solved this problem by adding.
contentHeight = max(contentHeight, frame.maxY)
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.
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()