1

I'm working on a requirement where I need to add the items in a UICollectionView dynamically.

Here is my code of ViewController

import UIKit

class ViewController: UIViewController {
    enum Direction {
        case Horizonatal
        case Verticle
    }

    var enumDirection: Direction = .Verticle
    var direction = "Verticle"
    var SectionsAndRows = [Int]()

    override func viewDidLoad() {
        super.viewDidLoad()
        SectionsAndRows.append(4)
        SectionsAndRows.append(3)
        SectionsAndRows.append(2)
        SectionsAndRows.append(1)
        //SectionsAndRows.append(5)
    }

    @IBOutlet var gridCollectionView: UICollectionView! {
        didSet {
            gridCollectionView.bounces = false
        }
    }

    @IBOutlet var gridLayout: UICollectionViewFlowLayout! {
        didSet {
            //gridLayout.stickyRowsCount = 0
            gridLayout.scrollDirection = .horizontal
            //gridLayout.stickyColumnsCount = 0
            gridLayout.minimumLineSpacing = 5
            gridLayout.minimumInteritemSpacing = 5
        }
    }
 }

// MARK: - Collection view data source and delegate methods

extension ViewController: UICollectionViewDataSource {

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return SectionsAndRows.count
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        print(SectionsAndRows[section])
        return SectionsAndRows[section]
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionViewCell.reuseID, for: indexPath) as? CollectionViewCell else {
            return UICollectionViewCell()
        }
        print("Current Section ==\(indexPath.section) CurrentRow ===\(indexPath.row) and its rows count ==\(SectionsAndRows[indexPath.section])")

        cell.titleLabel.text = ""
        cell.btn.addTarget(self, action: #selector(handleAdd(sender:)), for: .touchUpInside)
        cell.btn.tag = (indexPath.section * 1000) + indexPath.row
        if enumDirection == .Verticle {
            if indexPath.section == SectionsAndRows.count - 1 {
                cell.btn.setTitle("+", for: .normal)
            } else {
                cell.btn.setTitle("\(indexPath)", for: .normal)
            }

        }
        return cell
    }

    @objc func handleAdd(sender: UIButton) {
        // Perform some opration
    }
}

extension ViewController: UICollectionViewDelegateFlowLayout {

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

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

CollectionViewCell.swift

import UIKit

class CollectionViewCell: UICollectionViewCell {
    static let reuseID = "CollectionViewCell"

    @IBOutlet weak var btn: UIButton!
    @IBOutlet weak var titleLabel: UILabel!
}

If you run the code, it will show a Collection of 1 row and 1 column in each row. If you uncomment the last line of viewDidLoad() (SectionsAndRows.append(5)) function, then it works fine.

My observation is that the last section of the CollectionView will have the highest number of a column. Is that correct or is this a bug of a CollectionView?

Maciej Gad
  • 1,701
  • 16
  • 21
SandeepM
  • 2,601
  • 1
  • 22
  • 32
  • Can you state your question exactly? What is that you need help with? Your observation happens: when ```SectionsAndRows.append(5)``` is commented or when uncommented? – Starsky Dec 18 '19 at 14:03
  • @Starsky, I want to show 4 items in first section, 3 items in second section and so on. But all the section shows only 1 item. Now uncomment the last line. It will show all the items correctly. So, my question is, is this a bug or is there any work around for that? – SandeepM Dec 18 '19 at 17:42
  • I'm assuming you're setting the `UICollectionViewDelegate` and `UICollectionViewDataSource` in Storyboard, since I don't see it in your code anywhere. In that case it seems you are never reloading the data with `reloadData` after you adjust your `SectionsAndRows`, right? Or did you just not post that part? – creeperspeak Dec 18 '19 at 18:10
  • That I've set from the storyboard. Did you get a chance to run the code @creeperspeak – SandeepM Dec 19 '19 at 06:13
  • Do you have an image of your desired result? Do you want your individual sections to scroll horizontal, while the other sections stay still? Maybe you need a more complex approach to what you want to achieve. – Starsky Dec 19 '19 at 08:42

0 Answers0