【问题标题】:How to properly use a UIColor as a property如何正确使用 UIColor 作为属性
【发布时间】:2013-04-25 19:48:52
【问题描述】:

为什么我的颜色属性总是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

【问题讨论】:

  • 你怎么知道它总是null?另外,现在是color 还是iconColor
  • 在 initWithFrame 和 Debug 上设置断点。它应该进入 init 方法。如果它不进去,你的属性将永远为空。
  • 这个按钮是在 XIB 文件中定义的吗?
  • 合成你的颜色对象。
  • 自 Xcode 4.4 起您不必合成它

标签: objective-c properties uicolor


【解决方案1】:

您之前的评论说您正在使用界面构建器,这意味着在按钮上调用了不同的 init 方法。你需要实现:

- (id)initWithCoder:(NSCoder *)decoder
{
    if ((self = [super initWithCoder:decoder])) {
        // setup code
    }

    return self;
}

通常最好同时实现 initWithCoder:initWithFrame: 并让它们都在共享设置代码所在的位置调用 commonInit 方法。

【讨论】:

  • 只是实现 initWithCoder 的行为似乎是通过 [super init] 调用 initWithFrame;
  • initWithCoder 似乎重置了视图的框架属性。这应该发生吗?这个想法是在界面构建器中放置对象视图并调整其大小。即使 initWithFrame 没有被覆盖,也会发生这种情况。
  • ....那是因为 initWithCoder 应该调用 [super initWithCoder] 而不是 [super init]。对。
【解决方案2】:

尽量使用颜色RGB值,而不是直接定义颜色会更有效。

【讨论】:

  • 因为它将是一个可重用的界面控件,我想坚持使用 UIColors。理想情况下,控件的颜色属性将设置为选定的 UIColor,但默认为白色。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多