在集合视图中显示三个单元格

时间:2019-02-26 06:01:07

标签: ios swift uicollectionview

我制作了一个收集视图,以网格格式显示图像。代码如下:

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    @IBOutlet weak var myCollectionView: UICollectionView!
    let array:[String] = ["1", "2", "3"]

    override func viewDidLoad() {
        super.viewDidLoad()
        let itemSize = UIScreen.main.bounds.width/3 - 3

        let layout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0)
        layout.itemSize = CGSize(width: itemSize, height: itemSize + 100)

        layout.minimumInteritemSpacing = 3
        layout.minimumLineSpacing = 3

        myCollectionView.collectionViewLayout = layout


    }

    //Number of views
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return array.count
    }

    //Populate view
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! myCell
        cell.myImageView.image = UIImage(named: array[indexPath.row] + ".jpg")
        return cell

    }

现在,这样显示单元格...

enter image description here

但是我希望图像能像这样显示。 enter image description here

为此,我在上述给定代码行的末尾添加了此代码块...

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    if array.count == 3 {
        if array[indexPath.row] == "1" {
            return CGSize(width: 100, height: 200)
        }
        if array[indexPath.row] == "2" {
            return CGSize(width: 100, height: 100)
        }
        if array[indexPath.row] == "3" {
            return CGSize(width: 100, height: 100)
        }
    }
    return CGSize(width: 100, height: 100)
}

但是这样会显示图像...

enter image description here

我在这里做错什么了?还有更好的方法吗??

编辑1:如果有5张图片,则显示为...

enter image description here

1 个答案:

答案 0 :(得分:0)

您需要按照以下链接中的说明创建自定义布局。

Raywenderlich - Collection View Custom Layout Tutorial