Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift CollectionView changes size when imageview is inside

I have created a CollectionView with three items per row. If my cell includes just a view its working really fine like the picture shows:

here its shows like it should

But if I add an Imageview inside my view with equal constraints its going to look like this:

Collection view cell with imageview

Here is my Code for my CollectionView:

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

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

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let yourWidth = collectionView.bounds.width/3.0
    let yourHeight = yourWidth

    return CGSize(width: yourWidth, height: yourHeight)
}
like image 436
Silas Avatar asked Mar 04 '26 19:03

Silas


1 Answers

Seems like you are using a UICollectionViewFlowLayout.

This is not a bug or unexpected behavior. If there is something constrained to the edges of a cell's contentView, the layout will resize the cell to fit the contents. Instead of constraining the image to the leading/trailing and top/bottom anchors, constrain its center to the cell's center, this way it will not affect the cell's size. You may leave collectionView(_:layout:sizeForItemAt:) as is.

like image 163
WTEDST Avatar answered Mar 07 '26 10:03

WTEDST