给控件添加边框

经常会遇到给控件添加边框的需求:边框大体有两种实线和虚线

1、虚线边框的添加:
func clipDashedLine() {
       let borderLayer = CAShapeLayer()
       borderLayer.bounds = self.bounds
       borderLayer.position = CGPoint(x: self.bounds.midX, y: self.bounds.midY)
       borderLayer.path = UIBezierPath.init(rect: borderLayer.bounds).cgPath
       borderLayer.lineWidth = 1
       borderLayer.lineDashPattern = [3,3]
       borderLayer.fillColor = UIColor.clear.cgColor
       borderLayer.strokeColor = UIColor.red.cgColor
       self.layer.addSublayer(borderLayer)
   }
2、实现边框的添加:

a、最常采用的方式:

view.layer.borderWidth = 1
        view.layer.borderColor = UIColor.red.cgColor

b、其它方式:

func clipFullLine() {
       let borderLayer = CAShapeLayer()
       borderLayer.bounds = self.bounds
       borderLayer.position = CGPoint(x: self.bounds.midX, y: self.bounds.midY)
       borderLayer.path = UIBezierPath.init(rect: borderLayer.bounds).cgPath
       borderLayer.lineWidth = 1
       borderLayer.lineDashPattern = nil
       borderLayer.fillColor = UIColor.clear.cgColor
       borderLayer.strokeColor = UIColor.red.cgColor
       self.layer.addSublayer(borderLayer)
   }

该方式和虚线可以结合使用

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容