为什么我的颜色属性总是null
?
@interface StreamingMediaControlButton : UIButton
@property (strong, nonatomic) UIColor *color;
@end
@implementation StreamingMediaControlButton
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
_color = [UIColor whiteColor];
}
return self;
}
- (void)drawRect:(CGRect)rect
{
NSLog(@"color: %@", self.color);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, self.color.CGColor);
}
@end
最佳答案
您之前的评论说您正在使用界面生成器,这意味着在按钮上调用了不同的 init 方法。您需要实现:
- (id)initWithCoder:(NSCoder *)decoder
{
if ((self = [super initWithCoder:decoder])) {
// setup code
}
return self;
}
通常,最好同时实现 initWithCoder:
和 initWithFrame:
并让它们都调用一个 commonInit
方法,其中共享设置代码去吧。
关于objective-c - 如何正确使用 UIColor 作为属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16162142/