这让我发疯。我正在尝试更改CALayer子类的自定义属性“ mycolor”,这是我的代码:

#import "Circle"

@interface Circle()
   @property (nonatomic, strong) UIColor * mycolor;
   @property (nonatomic) float initial_angle;
   @property (nonatomic) float end_angle;
@end

@implementation Circle

@synthesize mycolor;
@synthesize initial_angle, end_angle;

- (id) init {
    self = [super init];
    if (self) {

        CGFloat red =  (CGFloat)random()/(CGFloat)RAND_MAX;
        CGFloat blue = (CGFloat)random()/(CGFloat)RAND_MAX;
        CGFloat green = (CGFloat)random()/(CGFloat)RAND_MAX;
        self.mycolor = [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
        self.backgroundColor =  [UIColor clearColor].CGColor;

    }
    return self;
}


-(void) changeColor {
    CGFloat red =  (CGFloat)random()/(CGFloat)RAND_MAX;
    CGFloat blue = (CGFloat)random()/(CGFloat)RAND_MAX;
    CGFloat green = (CGFloat)random()/(CGFloat)RAND_MAX;
    self.mycolor = [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
}

- (void) animate {
    float final = arc4random() % 360;
    float afrom = self.initial_angle;
    self.initial_angle = final;
    CABasicAnimation * anim = [CABasicAnimation animationWithKeyPath:@"initial_angle"];
    anim.fromValue = [NSNumber numberWithFloat:afrom];
    anim.toValue = [NSNumber numberWithFloat:final];
    anim.duration = 5;
    anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [self addAnimation:anim forKey:@"initial_angle"];

    final = arc4random() % 360;
    afrom = self.end_angle;
    self.end_angle = final;
    anim = [CABasicAnimation animationWithKeyPath:@"end_angle"];
    anim.fromValue = [NSNumber numberWithFloat:afrom];
    anim.toValue = [NSNumber numberWithFloat:final];
    anim.duration = 5;
    anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [self addAnimation:anim forKey:@"end_angle"];

}

- (void) drawInContext:(CGContextRef)ctx {

    CGContextMoveToPoint(ctx, 50, 50);
    CGContextAddArc(ctx, 50, 50, 50, initial_angle*M_PI/180, end_angle*M_PI/180, 0);
    CGContextClosePath(ctx);
    NSLog(@"%@", self.mycolor);

    CGContextSetFillColorWithColor(ctx, self.mycolor.CGColor);
    CGContextFillPath(ctx);

}

+ (BOOL)needsDisplayForKey:(NSString*)key {
    if ([key isEqualToString:@"initial_angle"]||
        [key isEqualToString:@"end_angle"]||
        [key isEqualToString:@"mycolor"]) {
        return YES;
    } else {
        return [super needsDisplayForKey:key];
    }
}

@end


changeColor和animate是公共方法。 Animate每秒钟被调用一次,并且每当用户点击de circle时都会更改一次color。

一切正常,除了在“ drawInContext”中mycolor始终为空。不知道为什么。

最佳答案

设置后,是否尝试过立即记录mycolor的值?

您的代码看起来不错,因此肯定发生了一些奇怪的事情。是否有可能在某个地方为mycolor创建了自定义的setter或getter方法,而未正确实现呢?

我假设您使用的是ARC-您是否尝试过直接设置mycolor ivar而不是通过setter设置? (在ARC中应该没问题-不会泄漏或意外释放)

09-25 17:18