为uiview设置单边边框

原生的 UIKit 并没有提供设置单边边框(border)的功能,view.layer.borderColorview.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))

效果如下:
Jietu20170916-220455.jpg

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值