0

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?enter image description here

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Rami
  • 115
  • 1
  • 2
  • 8
  • Let me ask it this way: You want to set the width of the cells in such a manner that there are 7 cells visible regardless of the screen width? – ZeMoon Apr 24 '19 at 05:47
  • It is almost the same as: https://stackoverflow.com/questions/39957826/how-do-i-change-the-size-of-a-2x2-uicollectionview-and-fit-the-whole-screen-swi/39958163#39958163 but you have to divide `collectionView.frame.width / 7` instead. – Ahmad F Apr 24 '19 at 05:55

4 Answers4

2

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)
RajeshKumar R
  • 15,445
  • 2
  • 38
  • 70
1

Hope this is What you want,

enter image description here

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!

caldera.sac
  • 4,918
  • 7
  • 37
  • 69
0

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

NavinBagul
  • 741
  • 7
  • 24
0

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.