简体   繁体   中英

collection view cell Hight and width in swift

collection view had multiple images working fine. it's showing like this

在此处输入图片说明

But i want show like this way

在此处输入图片说明

this is code of collection view cell

 let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
 layout.sectionInset = UIEdgeInsets(top: 10, left: 0, bottom: 20, right: 0)
 let width = UIScreen.main.bounds.width
 layout.itemSize = CGSize(width: width/2 , height: width/2 )
 layout.minimumInteritemSpacing = 0
 layout.minimumLineSpacing = 0
 collectionView!.collectionViewLayout = layout

Just implement some UICollectionViewDelegateFlowLayout methods to get the correct size and spacing of the UICollectionViewCells .

Example:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
    let cellSize = CGSize(width: (collectionView.bounds.width - (3 * 10))/2, height: 120)
    return cellSize
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat
{
    return 10
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
{
    let sectionInset = UIEdgeInsetsMake(10, 10, 10, 10)
    return sectionInset
}

Just change the size and spacing values according to your requirement.

Add this method on your viewcontroller

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
        return CGSize(width: ((self.view.frame.size.width/2) - 10), height: 255)
    }

尝试,

collectionViewCellImageView.contentMode = .scaleToFill

You can try to set minimum spacing for cell & line for collection view and implement the bellow delegate

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: (collectionView.frame.width/2) - 5, height: collectionView.frame.width/2)
    }

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