如何在Swift中为集合视图添加边框?

时间:2017-06-08 02:53:18

标签: ios swift

不是集合视图单元格,我通过在ViewController中应用特定的边框函数(如borderColor和cornerRadius方法)来解决这个问题。我在谈论用一个边框封装整个细胞视图,有点像这样:

The collection view cell that I want to achieve

非常感谢。

3 个答案:

答案 0 :(得分:2)

在ViewDidLoad函数中,只需添加此类型的行(选择您的值)。

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

答案 1 :(得分:1)

您需要为collectionView视图本身添加边框。这就是封装细胞的原因。您可以在viewDidLayoutSubviews:viewDidLoad:

中执行此操作

像这样:

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

答案 2 :(得分:0)

您可以使用UICollectionViewDelegateFlowLayout和以下方式执行此操作。

// 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)
}