Nikhil Muskur
Nikhil Muskur

Reputation: 210

Corner Radius for UIImageView not working for UICollectionViewCell with dynamic size

I have cell which consist of a UIImageView which has a height of 70% of the cell size and the rest of the 30% is used up by the label.

The cell's have a dynamic size which is calculated according to the device width.

I have made sure the cells are are square and the UIImageView contained within the cell's also has 1:1 ratio for their height and width

I am setting the corner radius of the UIImage in the cellForItem delegate method of the Collection View

cell.userImage.layer.cornerRadius = cell.userImage.bounds.width / 2
cell.userImage.clipsToBounds = true

The Image that I get is this

So can anyone point me in the right direction as why this is happening ? When should I set the corner radius of the Image in the cell lifecycle ?

This doesn't happen if I give the image view static size, but I want the size to be dynamic according to the screen size

Upvotes: 0

Views: 609

Answers (3)

Njuacha Hubert
Njuacha Hubert

Reputation: 566

hey use this delegate UICollectionViewDelegateFlowLayout to set the size for each item in cell. something like below

    ...

    collectionView.delegate = self

    ...

    // then make your view controller confirm to the UICollectionViewDelegateFlowLayout
    // then overide this method like below 
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

      CGSize(width: MyLayoutConstants.collectionViewItemWidth,
            height: collectionView.frame.height)
    }

this is just an example from my case. the main idea is that use the delagate above.

Upvotes: 0

Digs
Digs

Reputation: 193

try cell.userImage.layer.maskToBounds = true

Better to wrap imageView inside a UIView . Then set UIView propertiesbound.size.width/2

Upvotes: 1

tzonGoza
tzonGoza

Reputation: 406

You are taking the width of "bounds". Try taking the width/height of cell.userImage.

cell.userImage.layer.cornerRadius = cell.userImage.bounds.width / 2

Also, is the ratio of the image 1:1?

Upvotes: 0

Related Questions