簡體   English   中英

自定義CollectionView布局

[英]Custom CollectionView Layout

我想制作一個這樣的自定義單元:

在此處輸入圖片說明

這是我的代碼:

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

我的代碼有什么問題嗎?

盡管我真的不知道如何解決您的問題,但是我知道一個第三方庫可以完全滿足您的需求。 看一下這個。

您可以使用它來獲得所需的結果,或者可以看一下代碼,看看它是如何完成的。

PS該代碼在Objective-C中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM