在自定义view中
- (instancetype)initWithFrame:(CGRect)frame {
if (self == [super initWithFrame:frame]) {
CAShapeLayer *border = [CAShapeLayer layer];
border.strokeColor = [UIColor redColor].CGColor;
border.fillColor = nil;
border.path = [UIBezierPath bezierPathWithRect:self.bounds].CGPath;
border.frame = self.bounds;
border.lineWidth = 1.f;
border.lineCap = @"square";
border.lineDashPattern = @[@4, @4]; //可以修改查看不同效果
[self.layer addSublayer:border];
}
return self;
}```
当不是在
- (instancetype)initWithFrame:(CGRect)frame;
方法
而是在
- (instancetype)init;
我是这样写
(instancetype)init {
if (self == [super init]) {
}
return self;
}-
(void)layoutIfNeeded {
[super layoutIfNeeded];
CAShapeLayer *border = [CAShapeLayer layer];border.strokeColor = [UIColor redColor].CGColor;
border.fillColor = nil;
border.path = [UIBezierPath bezierPathWithRect:self.bounds].CGPath;
border.frame = self.bounds;
border.lineWidth = 1.f;
border.lineCap = @"square";
border.lineDashPattern = @[@4, @4];
[self.layer addSublayer:border];
}
在创建 CustonView的时候
CustonView *view = [[CustonView alloc] init];//WithFrame:CGRectMake(100, 100, 100, 100)];
view.frame = CGRectMake(100, 100, 100, 100);
[view layoutIfNeeded];
[self.view addSubview:view];