0

So today I was experimenting with Collection Views and ran into quite an interesting bug.

The bug is that the imageView circles which I had are never perfect, unless I scroll them off the screen. Their shape resembles that of a rhombus with rounded edges.

And after I scroll up and down again so that the top cells become temporarily out of sight, the cells which were out of sight are now perfect circles.

Here is my code for the cell class:

class FavouritesCollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var profilePicutreImageView: UIImageView!
    @IBOutlet weak var nameLabel: UILabel!

    override var bounds: CGRect {
        didSet {
            contentView.frame = bounds
        }
    }

    override func layoutSubviews() {
        profilePicutreImageView.layer.borderWidth = 2.0
        profilePicutreImageView.layer.masksToBounds = false
        profilePicutreImageView.layer.cornerRadius = profilePicutreImageView.frame.width/2
        profilePicutreImageView.layer.borderColor = UIColor.blackColor().CGColor
        profilePicutreImageView.clipsToBounds = true

    }
}

Any ideas about what this may be?

UPDATE---Here are the pictures of what is happening

Before: enter image description here

After: enter image description here

2 Answers2

1

I answered a similar question here

First, I would call super to layoutSubviews. After that, call layoutIfNeeded when you bind your data to the cell:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
          cellForItemAtIndexPath:(NSIndexPath *)indexPath
     UICollectionViewCell*cell = ...
     // Do your stuff here to configure the cell
     // Tell the cell to redraw its contentView        
     [cell layoutIfNeeded];
}
Community
  • 1
  • 1
Pablo Romeu
  • 2,033
  • 1
  • 13
  • 15
0

I think this is related to that you set the imageView's border in method layoutSubview which will be called multiple time during cell's lift cycle under different circumstances.

set the imageView's border in initWithFrame won't help if you init the cell with xib or in storyboard. Instead do it in awakeFromNib. Or do it in a more swift style way like such

@IBOutlet var avatar: UIImageView! {
        didSet {
            avatar.clipsToBounds = true
            avatar.layer.cornerRadius = 37.5
        }
    }
dopcn
  • 3,830
  • 3
  • 20
  • 29
  • I tried both the didSet and the awakeFromNib, but the bug has not gone away –  Sep 28 '15 at 13:01