原生的 UIKit 并没有提供设置单边边框(border)的功能,view.layer.borderColor
和view.layer.borderWidth
会把上下左右的边框一起设置。所以想设置单边只能自己来实现了。
画border
线的思路很简单,其实就是画一条直线,把这条直线添加到 view
的边缘即可。画直线的方法也有几种,有使用 UIKit 的 UIBezierPath
实现的,有使用Core Graphics
的。这里我使用UIBezierPath
实现:
大致实现如下:
let line = UIBezierPath(rect: CGRect(x: 0, y: self.frame.size.height / 2, width: self.frame.size.width, height: 1))//实例化一条宽度为1的直线
let lineShape = CAShapeLayer()//设置路径的画布
lineShape.path = line.cgPath //设置画布的路径为贝塞尔曲线的路径
lineShape.fillColor = UIColor.red.cgColor//设置颜色
self.view.layer.addSublayer(lineShape)//添加画布的 layer
我们可以把这些代码写在 draw
方法上,当然,如果想让所有的 UIView
都有这个功能,我们可以为 UIView
添加 extension
:
//为 uiview 扩展添加边框功能
extension UIView {
//画线
private func drawBorder(rect:CGRect,color:UIColor){
let line = UIBezierPath(rect: rect)
let lineShape = CAShapeLayer()
lineShape.path = line.cgPath
lineShape.fillColor = color.cgColor
self.layer.addSublayer(lineShape)
}
//设置右边框
public func rightBorder(width:CGFloat,borderColor:UIColor){
let rect = CGRect(x: 0, y: self.frame.size.width - width, width: width, height: self.frame.size.height)
drawBorder(rect: rect, color: borderColor)
}
//设置左边框
public func leftBorder(width:CGFloat,borderColor:UIColor){
let rect = CGRect(x: 0, y: 0, width: width, height: self.frame.size.height)
drawBorder(rect: rect, color: borderColor)
}
//设置上边框
public func topBorder(width:CGFloat,borderColor:UIColor){
let rect = CGRect(x: 0, y: 0, width: self.frame.size.width, height: width)
drawBorder(rect: rect, color: borderColor)
}
//设置底边框
public func buttomBorder(width:CGFloat,borderColor:UIColor){
let rect = CGRect(x: 0, y: self.frame.size.height-width, width: self.frame.size.width, height: width)
drawBorder(rect: rect, color: borderColor)
}
}
在需要设置的地方调用:
self.buttomBorder(width: 2, borderColor: UIColor(red: 1, green: 1, blue: 1, alpha: 0.2))
效果如下: