Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a background image to a UICollectionViewCell in Swift?

I had assumed that it would be easy to add a background image to a UICollectionViewCell, but I am having trouble figuring it out. I have a border image like this that I want to add to every cell in my UICollectionView.

border.png

enter image description here

I couldn't see an option to add it in the Interface Builder and I'm not sure which method to use on UICollectionViewCell programmatically.

I have seen these similar questions:

  • UICollectionView Cell with Image, change Background with click (image is already added)
  • How to add a background image to UICollectionView that will scroll and zoom will cells (UICollectionView, not UICollectionViewCell)
like image 351
Suragch Avatar asked Dec 25 '22 13:12

Suragch


1 Answers

I know this is a old question, with an accepted answer. But why not just set the border of the cell like so:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
    let cell  = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) 

        cell.layer.borderWidth = 1.5
        cell.layer.borderColor = UIColor.blueColor().CGColor
        cell.layer.cornerRadius = 4

  return cell
}

That way you don't need to use a image. Just adjust the borderWidth and cornerRadius until you get the desired effect.

like image 119
the_pantless_coder Avatar answered Dec 31 '22 12:12

the_pantless_coder