設定虛線

weixin_34402408發表於2017-06-02

在自定義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];

相關文章