【问题标题】:How to inherit from UIColor correctly or how to access UIColor subclass property如何正确继承 UIColor 或如何访问 UIColor 子类属性
【发布时间】:2014-01-19 02:29:18
【问题描述】:

这是我的代码:

@interface SubColor : UIColor

@property (atomic, assign) int key;

+ (id)colorWithkey:(int)key color:(UIColor *)color;

@end

@implementation SubColor

- (id)initWithCGColor:(CGColorRef)cgColor withkey:(ThemeConfigKey)key{
    if (self = [super initWithCGColor:cgColor]) {
        _key = key;
    }

    return self;
}

- (BOOL)isKindOfClass:(Class)aClass{
    NSLog(@"isKindOfClass:%@", NSStringFromClass(aClass));
    return [super isKindOfClass:aClass];
}

+ (id)colorWithkey:(int)key color:(UIColor *)color{
    SubColor *subColor = [[SubColor alloc] initWithCGColor:color.CGColor withkey:key];
    if([subColor isKindOfClass:[SubColor class]]){
        NSLog(@"123");
    }

    return subColor;
}

@end

NSLog 不输出@"isKindOfClass:%@" 和@"123"。那是因为 SubColor 实例只是一种 UIColor 类而不是 SubColor 类。当颜色在其他地方使用时,如何知道颜色是我自己的 SubColor?

另外,here 中讨论的一些方法由于某种原因并不完美。因为 UIColor 在某些情况下会被系统重用!如果两种颜色包含相等的 RGB 值,则可以将具有“A”颜色的关联键替换为具有“B”颜色的关联键。这让我抓狂!

【问题讨论】:

  • 为了清楚起见,您是说在另一个问题中使用该解决方案的问题是因为您可能需要具有相同 RGB 值且具有两个不同主题键的两种颜色?如果UIColor 在这种情况下返回相同的实例,那将是一个问题。
  • @rmaddy 两种颜色具有相同的 RGB 值,具有两个不同的主题键是我需要的,我的问题是 UIColor 有时会被系统重用。通过我对 NSLog 输出的练习,UITableViewCell 上的 textLabel使用“a”键和值“0xffffff”设置文本颜色,在单元格布局子视图方法之后,将 textLabel 文本颜色替换为具有“b”键和值“0xffffff”的颜色。通过跟踪,带有“b”键和值“0xffffff”的颜色被navigationBar titleView使用,它也是一个UILabel。
  • 对,这证实了我认为你的意思。由于UIColor 似乎为某些常见颜色返回了一些固定实例,这使您想做的事情变得非常困难。如何创建你的类,使其扩展 NSObject 而不是 UIColor 并具有两个属性 - 你的密钥和 UIColor
  • 这也很难,我的类也应该可以通过系统UILabel textColor和其他使用UIColor的方法来访问。并非所有颜色都是由我的方法创建的。从 UIColor 继承符合我的要求。但是现在我不知道如何判断 UIColor 是我的 subColor。那是克雷!
  • 那你就卡住了。 UIColor 不能正确支持子类化,因为它返回一些固定的颜色实例,并且您的需要阻止使用具有 UIColor 属性的类。您需要另一种方法来跟踪颜色与哪个主题相关联。在不了解您的需求的情况下,很难提供其他建议。

标签: ios objective-c


【解决方案1】:

正如 rmaddy 在评论中所说,UIColor 不支持子类化。我只是在猜测您此时的需求,但是请考虑创建一个 UIColor 类别。它可能会解决您的问题。

我认为您只想在一个配置中拥有一组颜色,而在另一个配置中拥有另一组颜色。编写一个UIColor 类别可以做到这一点。

【讨论】:

    【解决方案2】:

    那是因为 UIColor 有点像Class Clusters。以及Class Clusters 的 Cocoa Fundamentals Guide 中的详细描述。

    The class cluster architecture involves a trade-off between simplicity and extensibility: Having a few public classes stand in for a multitude of private ones makes it easier to learn and use the classes in a framework but somewhat harder to create subclasses within any of the clusters. However, if it’s rarely necessary to create a subclass, then the cluster architecture is clearly beneficial. Clusters are used in the Foundation framework in just these situations.

    文档中也提到了如何在类簇中创建子类。

    虽然我已经通过其他方式解决了我的问题。我认为有必要在这里列出相对链接器并关闭答案。

    希望这可以帮助遇到类似问题的其他人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-02
      • 2015-06-21
      • 2017-05-26
      • 1970-01-01
      • 2011-12-22
      相关资源
      最近更新 更多