Twitter khuong291
Twitter khuong291

Reputation: 11700

Custom CollectionView Layout

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?

Upvotes: 0

Views: 159

Answers (1)

ebby94
ebby94

Reputation: 3152

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.

Upvotes: 1

Related Questions