Suragch
Suragch

Reputation: 511586

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:

Upvotes: 4

Views: 8063

Answers (3)

the_pantless_coder
the_pantless_coder

Reputation: 2297

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.

Upvotes: 6

Jayesh Miruliya
Jayesh Miruliya

Reputation: 3317

let View=UIView()
View.backgroundColor=UIColor(patternImage:UIImage(named:"border.png")!)
cell.backgroundView=View

in uicollectionview cellForItemAtIndexPath method

Upvotes: 4

Abizern
Abizern

Reputation: 150575

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

Upvotes: 1

Related Questions