为uiview设置单边边框
原生的 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.cgPathlineShape.fillColor = color.cgColorself.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)) 效果如下:
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
