自定义更改单元格底部边框的颜色
Posted
技术标签:
【中文标题】自定义更改单元格底部边框的颜色【英文标题】:Custom change color of cell bottom border 【发布时间】:2019-08-03 10:53:42 【问题描述】:我需要在 UICollectionView 中更改底部单元格的颜色,在这个 question 中,我只是这样做 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
【问题讨论】:
【参考方案1】:我不会尝试将其添加为边框,而是添加两个图层,因为这样更容易。类似的东西:
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 完全制作成您需要的形状,只是为了达到目的。
【讨论】:
已编辑。只需将绘制形状方法更改为返回所需形状的方法。也就是向其他顶点添加曲线。以上是关于自定义更改单元格底部边框的颜色的主要内容,如果未能解决你的问题,请参考以下文章
分组 UITableView 自定义绘制单元格,而不更改背景颜色?
在uitableview中选择时如何更改自定义单元格图像和标签字体颜色?
在普通样式的 UITableView 中更改自定义 UITableViewCell 单元格的背景颜色