在UIView子类中使用的CAShapeLayer不起作用

See*_*ega 7 iphone core-animation ios

我尝试了几个小时用CAShapeLayer在我的UIView周围画一个虚线边框,但是我没有显示它.
ScaleOverlay.h

#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>

@interface ScaleOverlay : UIView <UIGestureRecognizerDelegate> {
    CAShapeLayer *shapeLayer_;
}
@end
Run Code Online (Sandbox Code Playgroud)

ScaleOverlay.m

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
    self.backgroundColor = [UIColor redColor];
    self.alpha = 0;
    //Round corners
    [[self layer] setCornerRadius:8.f];
    [[self layer] setMasksToBounds:YES];
    //Border
    shapeLayer_ = [[CAShapeLayer layer] retain];

    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, frame);
    shapeLayer_.path = path;
    CGPathRelease(path);
    shapeLayer_.backgroundColor = [[UIColor clearColor] CGColor];
    shapeLayer_.frame = frame;
    shapeLayer_.position = self.center;

    [shapeLayer_ setValue:[NSNumber numberWithBool:NO] forKey:@"isCircle"];
    shapeLayer_.fillColor = [[UIColor blueColor] CGColor];
    shapeLayer_.strokeColor = [[UIColor blackColor] CGColor];
    shapeLayer_.lineWidth = 4.;
    shapeLayer_.lineDashPattern = [NSArray arrayWithObjects:[NSNumber numberWithInt:8], [NSNumber numberWithInt:8], nil];
    shapeLayer_.lineCap = kCALineCapRound;
}
return self;
}
Run Code Online (Sandbox Code Playgroud)

我在Superview中绘制了一个红色矩形,但没有绘制边框.从源示例中复制了这个,希望它可以工作,但事实并非如此.

Bra*_*son 16

您永远不会添加shapeLayer为UIView图层的子图层,因此它永远不会显示在屏幕上.尝试添加

[self.layer addSublayer:shapeLayer_];
Run Code Online (Sandbox Code Playgroud)

在您的-initWithFrame:方法中设置CAShapeLayer之后.

更好的是,你可以尝试通过覆盖以下类方法来使你的UIView的支持层成为CAShapeLayer:

+ (Class) layerClass 
{
    return [CAShapeLayer class];
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以直接处理视图的图层,并消除其他CAShapeLayer实例变量.