iOS 虚线分割线

2019-11-30  本文已影响0人  倪大头

效果如下:


image.png

继承一个UIView,重写drawRect方法:

DashLineView.h:

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface DashLineView : UIView

@end

NS_ASSUME_NONNULL_END

DashLineView.m:

#import "DashLineView.h"

@implementation DashLineView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor blackColor];
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 虚线颜色
    CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
    // 虚线宽度
    CGContextSetLineWidth(context, 5);
    // 绘制起点
    CGContextMoveToPoint(context, 0, 0);
    // 绘制终点
    CGContextAddLineToPoint(context, self.frame.origin.x + self.frame.size.width, 0);
    // 虚线间隔
    CGFloat array[] = {3, 4};
    CGContextSetLineDash(context, 0, array, 2);
    CGContextStrokePath(context);
}

@end
上一篇 下一篇

猜你喜欢

热点阅读