Christopher Chu
Christopher Chu

Reputation: 23

How do I add a border to a Collection View in Swift?

Not a collection view cell, I figured that out by applying specific border functions such as borderColor and cornerRadius methods in my ViewController. I'm talking about encapsulating the whole view of cells with one border, kind of like this:

The collection view cell that I want to achieve

Much appreciated.

Upvotes: 0

Views: 4762

Answers (3)

Bryan Gula
Bryan Gula

Reputation: 490

You need to add a border to collectionView view itself. That is what encapsulates the cells. You can do this either in the viewDidLayoutSubviews: or viewDidLoad:

Like this:

collectionView.layer.borderWidth = 2.0
collectionView.layer.cornerRadius = 5.0

Upvotes: 1

eNeF
eNeF

Reputation: 3280

You can do that using UICollectionViewDelegateFlowLayout and here's how.

// your margin for top, botom, right, left
let inBetweenMargin: CGFloat = 30

let collectionViewSize: CGSize = {

    // define the max width of your collection view
    let screen = UIScreen.main.bounds.size.width

    // your margin for top, botom, right, left
    let inBetweenMargin: CGFloat = 30

    // left, mind, right 'inBetweenMargin * 3'
    let cellSquareSize = screen - (inBetweenMargin * 3);

    return CGSize(width: cellSquareSize, height: cellSquareSize)
}()

// MARK: - UICollectionViewDelegateFlowLayout

// computed cell size
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    return collectionViewSize
}

// for spacing in between cells
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {

    return inBetweenMargin
}

// for spacing in between cells
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {

    return inBetweenMargin
}

// we define inset for us to achieved an equal margin for top, botom, right, left
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {

    return UIEdgeInsets(top: inBetweenMargin, left: inBetweenMargin, bottom: inBetweenMargin, right: inBetweenMargin)
}

Upvotes: 0

elk_cloner
elk_cloner

Reputation: 2149

in your ViewDidLoad function, just add this type of line(choose your value).

collectionView.layer.borderColor = UIColor.green.cgColor
collectionView.layer.borderWidth = 3.0
collectionView.layer.cornerRadius = 3.0//if you want corner radius.addtional

enter image description here

Upvotes: 5

Related Questions