使UICollectionViewCell与UICollectionView的宽度相同

时间:2019-10-13 13:39:02

标签: ios swift uicollectionview uicollectionviewcell

正在写此问题仅供参考,以帮助遇到我同样问题的任何人。在SO和Google搜索中,这里的许多答案都没有提供完整的解决方案。所以我在这里回答我自己的问题

1 个答案:

答案 0 :(得分:2)

这是可以正常设置宽度和高度的代码

import UIKit

class MyViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {

    @IBOutlet weak var myCollectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()

        myCollectionView.delegate = self
        myCollectionView.reloadData()
    }

    //Other methods here

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
                        sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = collectionView.frame.size.width
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) //Put your Cell Identifier istead of Cell
        let height = cell.contentView.frame.height

        return CGSize(width: width, height: height)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
    {
        return .zero
    }
}