Search code examples
iosobjective-cuiimageviewuicollectionviewsdwebimage

UIImageView should be as circle view instead of diamond in UICollectionView


I have UICollectionView with UIImageView on it (as shown at image).

enter image description here

And I want to make it as circle view. But, when I running application, it's appearing as diamond (image below).

enter image description here

In (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { I setup it as

[cell.photo setImageWithURL:[NSURL URLWithString:url] usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];

    cell.photo.layer.cornerRadius = cell.photo.bounds.size.width / 2;
    cell.photo.layer.masksToBounds = NO;
    cell.photo.clipsToBounds = YES;

For setup image I used libs SDWebImage

And I'm sure, that cornerRadius value is correct (it's half of image width). Also I didn't make any manual changes in storyboard properties (position set as auto layout). What I missed?


Solution

  • Your problem is that cell can be re-layout after cellForItemAtIndexPath: and size of cell will be changed after it.

    Solutions for you: 1) Put cell.photo.layer.cornerRadius = cell.photo.bounds.size.width / 2; into

    - (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
    

    2) Create custom class for your UICollectionCell and override layoutSubviews function:

    - (void)layoutSubviews {
        [super layoutSubviews];
        self.photo.layer.cornerRadius = self.frame.size.width / 2.0;
    }