4

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:

Community
  • 1
  • 1
Suragch
  • 364,799
  • 232
  • 1,155
  • 1,198
  • I tried adding it in IB, but there wasn't a similar way to add it like I would with a UIButton. – Suragch Oct 03 '15 at 10:58

3 Answers3

6

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.

the_pantless_coder
  • 2,207
  • 1
  • 15
  • 30
  • 1
    I think when I wrote the question I still hadn't learned how to do borders on a layer. I subsequently added that as an update to [this answer](http://stackoverflow.com/a/31735229/3681880). So yes, your answer here is a better solution to my original problem (+1 for that). But since my question asked how to add a background image, I should keep the accepted answer. Not all background images will necessarily be a border. – Suragch Aug 07 '16 at 15:13
3
let View=UIView()
View.backgroundColor=UIColor(patternImage:UIImage(named:"border.png")!)
cell.backgroundView=View

in uicollectionview cellForItemAtIndexPath method

Jayesh Miruliya
  • 2,959
  • 1
  • 20
  • 21
  • 1
    Not using IB is ok, too. I couldn't figure out either way, so this way is helpful to know, too. – Suragch Oct 03 '15 at 13:05
1

Add a UIImageView to your CollectionViewCell and set this image as the image.

Abizern
  • 129,329
  • 36
  • 198
  • 252