简体   繁体   中英

Make UICollectionViewCell same width as UICollectionView

Am writing this question just as a reference and to help anyone facing the same issue I faced. Many answers here at SO and in google search didn't provide a complete solution. So Here I answer my own question

Here is the code that works and sets both width and height correctly

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM