Ben
Ben

Reputation: 4867

Strange Border on UICollectionViewCell - Swift

I have created a subclass for a UICollectionViewCell, which looks like this...

import Foundation
import UIKit
class GroupCollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var name: UILabel!
    @IBOutlet weak var subject: UILabel!
}

As soon as I override the drawRect function like this...

override func drawRect(rect: CGRect) {
    self.layer.cornerRadius = 4
}

I get a strange border/shadow on the top and right of each cell (background colour set in storyboard)...

Border on top and right of each cell

Note that even if I take out the self.layer.cornerRadius line, the borders still appear, so presumably I've missed something out at the drawRect function - I'm just not sure what.

What makes this especially peculiar, is that when I run the code on a iPhone 6+ or wider device, the problem goes away.

The only other (presumably) relevant code, is that which I use to size the cells appropriately in the view controller:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    let size = collectionView.frame.width
    return CGSize(width: (size/3)-8, height: (size/3)-8)
}

What is the grey border/shadow, and how can I get rid of it? Many thanks in advance!

Upvotes: 0

Views: 1137

Answers (2)

nerowolfe
nerowolfe

Reputation: 4817

I can only suggest to make a little hack: Adding this lines to drawRect

        self.layer.borderWidth = 1
        self.layer.borderColor = COLOR_OF_GRPUP_CELL

Upvotes: 1

TwoStraws
TwoStraws

Reputation: 13127

I suspect this is probably just an implementation quirk that appears because you're not quite doing things the way Apple wants. Unless you're subclassing UIView, you should call super.drawRect() in your own drawRect() method. Furthermore, drawRect() isn't really the right place to set cornerRadius: you should set that once, perhaps when the cell is created, then forget about it.

You might find Apple's reference for UIView and drawRect useful:

If you subclass UIView directly, your implementation of this method does not need to call super. However, if you are subclassing a different view class, you should call super at some point in your implementation.

One more thing: if you can avoid overriding drawRect() you should; it does have a performance impact.

Upvotes: 1

Related Questions