Search code examples
iosswiftuicollectionviewuicollectionviewlayout

Display UICollectionView with 2 columns of equal size square cells


I'm trying to accomplish the following:

enter image description here

I've followed the answer in this question, but I get the image below:

enter image description here

This is the code for the collection view controller:

class MainMenuViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {



    @IBOutlet var collectionView: UICollectionView!
    @IBOutlet weak var dateTimeLabel: MarqueeLabel!
    @IBOutlet weak var iconButton: UIButton!
    @IBOutlet var imageView: UIImageView!

    var iconButtonTimer: Timer!
    var upDateTimer: Timer!

    var statusString: String!
    var alertTitle: String!
    var networkStatusString: String!




    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView.dataSource = self
        collectionView.delegate = self

        collectionView.register(UINib.init(nibName: "MainMenuCell", bundle: nil), forCellWithReuseIdentifier: "MainMenuCell")

        collectionView.collectionViewLayout = MainMenuLayout()
    }


    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 8
    }

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

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        print(#function)
        let padding: CGFloat =  50
        let collectionViewSize = collectionView.frame.size.width - padding

        return CGSize(width: collectionViewSize/2, height: collectionViewSize/2)
    }




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

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MainMenuCell", for: indexPath)

         cell.backgroundColor = UIColor.red

        return cell
    }
}

And this is the storyboard...

enter image description here


Solution

  • Conform to UICollectionViewDelegateFlowLayout and implement

    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        insetForSectionAt section: Int) -> UIEdgeInsets {
    
        return UIEdgeInsetsMake(10, 10, 10, 10)
    }
    

    Also comment this line

    collectionView.collectionViewLayout = MainMenuLayout()
    

    as no need for a custom layout to accomplish what you want

    enter image description here