在项目中遇到在cell中有一条虚线的设计,项目中的做法是:设置label,变成虚线,代码如下
首先声明:@property (nonatomic, strong) UILabel *line;
使用懒加载初始化数据
-(UILabel *)line{
if (!_line) {
_line = [[UILabel alloc] init];
[self.contentView addSubview:_line];
}
return _line;
}
设置frame和虚线 self.line.frame = CGRectMake(0, 20, cellWidth-2*marginX, 1);
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.position = CGPointMake(1, 2);
shapeLayer.fillColor = nil;
// 设置虚线颜色
shapeLayer.strokeColor = DB_GrayLine.CGColor;
// 3.0f设置虚线的宽度
shapeLayer.lineWidth = 1.0f;
shapeLayer.lineJoin = kCALineJoinRound;
// 3=线的宽度 4=每条线的间距
shapeLayer.lineDashPattern = @[@3, @4];
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, 0, 0);
CGPathAddLineToPoint(path, NULL, _line.frame.size.width,0);
shapeLayer.path = path;
CGPathRelease(path);
[_line.layer addSublayer:shapeLayer];
就完成了
可以根据自己的需求改变线的间距 ,// 3=线的宽度 4=每条线的间距
shapeLayer.lineDashPattern = @[@3, @4];