UICollectionViewCell Border / Shadow
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 importedUIKit
. - If you also want to add shadow, then see this answer.
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;
}