自定义CollectionView布局

时间:2016-07-11 02:48:09

标签: ios swift collectionview

我想制作一个这样的自定义单元格:

enter image description here

这是我的代码:

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)
        }
    }
}

我的代码有问题吗?

1 个答案:

答案 0 :(得分:1)

虽然我真的不知道如何解决您的问题,但我知道第三方图书馆正是您想要的。 Check this out.

您可以使用它来获得所需的结果,或者查看代码并查看它是如何完成的。

P.S。代码在Objective-C中。

相关问题