0

I want to make a custom cell like this:

enter image description here

Here is my code:

import UIKit

class ViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {

    @IBOutlet var collectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView.delegate = self
        collectionView.dataSource = self
    }

    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

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

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ImageCollectionViewCell", forIndexPath: indexPath) as! ImageCollectionViewCell
        if indexPath.row == 0 {
            cell.imgView.image = UIImage(named: "1")
        } else if indexPath.row == 1 {
            cell.imgView.image = UIImage(named: "2")
        } else {
            cell.imgView.image = UIImage(named: "3")
        }
        return cell
    }

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        let screenWidth = UIScreen.mainScreen().bounds.width
        if indexPath.row == 0 {
            return CGSize(width: screenWidth / 2, height: screenWidth)
        } else if indexPath.row == 1 {
            return CGSize(width: screenWidth / 2, height: screenWidth / 2 - 20)
        } else {
            return CGSize(width: screenWidth / 2, height: screenWidth / 2 - 20)
        }
    }
}

Is there any wrong with my code?

halfer
  • 19,824
  • 17
  • 99
  • 186
Twitter khuong291
  • 11,328
  • 15
  • 80
  • 116
  • I don't know which iOS version you were in, but from iOS 12.0 we have something called ```UICollectionViewLayout``` class which can be subclassed that can achive this type of layout. Please see https://developer.apple.com/documentation/uikit/views_and_controls/collection_views/layouts/customizing_collection_view_layouts – Abdul Momen May 24 '21 at 11:20

1 Answers1

1

Though I don't really know how to fix your issue, I know a third party library that exactly does what you want. Check this out.

You can use it to get your desired result or perhaps look into the code and see how it is done.

P.S. The code is in Objective-C.

ebby94
  • 3,131
  • 2
  • 23
  • 31