自定义更改单元格底部边框的颜色

Custom change color of cell bottom border

我需要更改 UICollectionView 中底部单元格的颜色,在此 just I do this

我需要为底部单元格设置颜色,例如 this

let border = CALayer()
let width = CGFloat(2.0)
border.borderColor = UIColor(red: 184/255, green: 215/255, blue: 215/255, alpha: 1).cgColor
border.frame = CGRect(x: 0, y: cell.frame.size.height - width, width: cell.frame.size.width, height: cell.frame.size.height)
border.borderWidth = width
cell.layer.addSublayer(border)
cell.layer.masksToBounds = true

我不会尝试将其添加为边框,而是添加两层,因为这样更容易。像这样的东西:

 override func layoutSubviews() {
    super.layoutSubviews()

    backgroundShape = CAShapeLayer.init()
    backPath = UIBezierPath.init(rect: self.bounds)// Use your path
    backgroundShape.path = backPath.cgPath
    backgroundShape.fillColor = UIColor.blue.cgColor//border color in your case
    self.layer.addSublayer(backgroundShape)

    foregroundShape = CAShapeLayer()
    forgroundPath = UIBezierPath.init(rect: CGRect.init(x: 0, y: -20, width: self.bounds.width, height: self.bounds.height))// Use your path with  a little negative y
    foregroundShape.path = forgroundPath.cgPath
    foregroundShape.fillColor = UIColor.yellow.cgColor//white in your case
    self.layer.addSublayer(foregroundShape)  
}

详细解答:

class BorderedCell: UICollectionViewCell{

var backgroundShape: CAShapeLayer!
var backPath: UIBezierPath!
var foregroundShape: CAShapeLayer!
var forgroundPath: UIBezierPath!




override func layoutSubviews() {
    super.layoutSubviews()

    backgroundShape = CAShapeLayer.init()
    backPath = drawCurvedShape(with: 0)
    backgroundShape.path = backPath.cgPath
    backgroundShape.fillColor = UIColor(red:0.76, green:0.86, blue:0.86, alpha:1.0).cgColor
    self.layer.addSublayer(backgroundShape)

    foregroundShape = CAShapeLayer()
    forgroundPath = drawCurvedShape(with: -8)
    foregroundShape.path = forgroundPath.cgPath
    foregroundShape.fillColor = UIColor.white.cgColor
    self.layer.addSublayer(foregroundShape)
}


func drawCurvedShape(with startingY: CGFloat) -> UIBezierPath{
    let path = UIBezierPath.init()
    path.move(to: CGPoint.init(x: 0, y: startingY))
    path.addLine(to: CGPoint.init(x: self.bounds.width, y: startingY))
    path.addLine(to: CGPoint.init(x: self.bounds.width, y: self.bounds.height + startingY - 30))
    path.addQuadCurve(to: CGPoint.init(x: self.bounds.width - 30, y: self.bounds.height + startingY), controlPoint: CGPoint.init(x: self.bounds.width, y: self.bounds.height + startingY))
    path.addLine(to: CGPoint.init(x: 0, y: self.bounds.height + startingY))
    path.addLine(to: CGPoint.init(x: 0, y: startingY))
    path.close()

    return path
}
}

输出:

我没有将 drawShape 完全按照您需要的形状制作,只是为了达到目的。