Search code examples
subclassuicolorredefine

How to replace existing UIColors


I am trying to make a theming system for my app. Is there a way to redefine the default UIColors? I already tried to subclass UIColor:

//.h file

#import <UIKit/UIKit.h>

@interface UIColor(UIColor_themeColor)

+ (UIColor *)blackColor;

@end

//.m file

#import "UIColor+themeColor.h"
#import "DeviceColor.h"

@implementation UIColor(UIColor_themeColor)

+ (UIColor *)blackColor {
    return [self  blackColor];
}

@end

But then I get the warning Category is implementing a method which will also be implemented by its primary class which is understandable, and the app will crash if I build it.

Is there a way do what I like to do?


Solution

  • The preamble you'll get from everyone, I think: doing what you want to do is a bad idea as a method called blackColor should return the colour black. Methods should always be appropriately named.

    Post-preamble:

    Use method swizzling. You can't do it directly through declarations but because the Objective-C runtime is dynamic, you can switch the implementations of methods at runtime. You need to talk to the runtime directly, with its C API, but it's not too tricky.

    Mike Ash's guide walks you through the theory and shows you the code, much more clearly than I'm likely to here.