Question

When building an iPad App, how can you draw a border around a UICollectionViewCell?

More details: I implemented a class ProductCell which extends UICollectionViewCell. Now, I would like to assign some fancy details, e.g. a border, shadow, etc. However, when trying to use something like this here, Xcode tells me that the receiver type 'CALayer' is a forward declaration.

Was it helpful?

Solution

Just for a bit more implementation:

#import <QuartzCore/QuartzCore.h>

in your.m

Make sure your class implements

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath; 

as this is where the cell is setup.

You can then change cell.layer.background (only available once quartz is imported)

See below

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    MyCollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"pressieCell" forIndexPath:indexPath];
    //other cell setup here

    cell.layer.borderWidth=1.0f;
    cell.layer.borderColor=[UIColor blueColor].CGColor;

    return cell;
}

OTHER TIPS

Swift

Updated for Swift 3

Assuming you have your Collection View set up with the required methods, you can just write a few lines of code to add the border.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell
    cell.myLabel.text = self.items[indexPath.item]
    cell.backgroundColor = UIColor.cyan 
    
    // add a border
    cell.layer.borderColor = UIColor.black.cgColor
    cell.layer.borderWidth = 1
    cell.layer.cornerRadius = 8 // optional
    
    return cell
}

Notes

  • It is not necessary to import QuartzCore in Swift if you have already imported UIKit.
  • If you also want to add shadow, then see this answer.

You need to include the framework QuartzCore and import the header into your class:

#import <QuartzCore/QuartzCore.h>

Swift 4

cell.layer.borderColor = UIColor.black.cgColor
cell.layer.borderWidth = 1

Add it in datasource method, after creating the cell

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath)
     cell.layer.borderColor = UIColor.black.cgColor
     cell.layer.borderWidth = 1
}

I think it is better to add this config into your custom cell implementation, not in datasource delegate method.

cell.layer.borderColor = UIColor.black.cgColor
cell.layer.borderWidth = 1
cell.layer.cornerRadius = 8 // optional
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top