这让我疯了。我正在尝试更改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每秒调用一次并更改颜色。
除了在“drawInContext”中mycolor始终为null之外,一切正常。不知道为什么。
答案 0 :(得分:1)
您是否尝试在设置后立即记录mycolor的值?
你的代码看起来很合理,所以肯定会发生一些奇怪的事情。您是否有可能在某处为mycolor创建了自定义setter或getter方法而未正确实现?
我假设您正在使用ARC - 您是否尝试过直接设置mycolor ivar而不是通过setter? (在ARC中应该没问题 - 它不会泄漏或意外释放)
答案 1 :(得分:0)
@synthesize mycolor = _mycolor;
_mycolor = [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
尝试在init方法和drawInContext中使用_mycolor。
CGContextSetFillColorWithColor(ctx, self.mycolor.CGColor);
我认为在drawInContext中你可以使用实例变量而不是属性。
答案 2 :(得分:0)
CALayer
的正确初始化程序为+layer
,您应该覆盖+layer
方法,而不是甚至根本不会被调用的-init
。