1、創建UIView分類 UIView+Extension.h
在.h文件 聲明方法如下:
/**
* 給UI控件畫虛線
* @param lineColor 虛線顏色
* @param fillColor 填充色
* @param radius 虛線圓角
* @param lineWidth 虛線寬度
* @param type 虛線類型 "butt", "round" and "square"
* @return 返回 生成的虛線view
*/
- (UIView *)drawDotLineWithLineColor:(UIColor *)lineColor withFillColor:(UIColor *)fillColor withCornerRadius:(CGFloat)radius withLineWidth:(CGFloat)lineWidth AndLineType:(NSString *)type;
2、在.m文件 實現方法如下
//虛線
- (UIView *)drawDotLineWithLineColor:(UIColor *)lineColor withFillColor:(UIColor *)fillColor withCornerRadius:(CGFloat)radius withLineWidth:(CGFloat)lineWidth AndLineType:(NSString *)type {
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.strokeColor = lineColor.CGColor;
shapeLayer.fillColor = fillColor.CGColor;
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:radius];
shapeLayer.path = path.CGPath;
shapeLayer.frame = self.bounds;
shapeLayer.lineWidth = lineWidth;
if (type) {
shapeLayer.lineCap = type;
}else{
shapeLayer.lineCap = @"square";
}
//虛線每段長度和間隔
shapeLayer.lineDashPattern = @[@(2), @(2)];
[self.layer addSublayer:shapeLayer];
return self;
}
使用到虛線的時候 使用UI對象直接調用上面方法即可如:
[label drawDotLineWithLineColor:[UIColor redColor] withFillColor:[UIColor clearColor] withCornerRadius:2 withLineWidth:1 AndLineType:nil];