iOS 给UI控件画虚线(带圆角)

本文介绍了一种在iOS开发中使用UIView分类为UI控件绘制虚线的方法。通过自定义UIView+Extension分类,可以轻松地给任何UIView添加带有特定颜色、圆角、线宽及线型的虚线边框。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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];





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值