How to automatically choose between NSColor and UIColor for the correct build system? (Using a #define, or something)
Asked Answered
C

3

11

I'm trying to make a NSObject subclass that will have a lot of methods that return colors, so I wanna return UIColor if I'm building for iOS or NSColor if I'm building for OS X.
This is kind of a pseudo-code of what the expected behaviour should be:

#define COLOR #if TARGET_OS_IPHONE UIColor #elif TARGET_OS_MAC NSColor #endif

+ (COLOR *)makeMeColorful;

Is it possible to do something like this instead of making 2 methods for each of my object's method (one for iOS and another for OS X)?

Chasechaser answered 14/2, 2014 at 19:3 Comment(1)
See #15323609Windermere
E
15

This is absolutely doable. SKColor from SpriteKit for example, is defined like:

#if TARGET_OS_IPHONE
#define SKColor UIColor
#else
#define SKColor NSColor
#endif

And then utilized like this:

SKColor *color = [SKColor colorWithHue:0.5 saturation:1.0 brightness:1.0 alpha:1.0];

This simply takes advantage of the fact that UIColor and NSColor share some of their class methods.

Evan answered 14/2, 2014 at 19:7 Comment(2)
Very clever Apple. ;)Appassionato
Note that NSColor and UIColor don't share all their API, though, so you have to be careful not to call methods that exist only on one or the other.Zollie
B
8

If you are using Swift try something in the lines of

#if os(macOS)
    typealias Color = NSColor
#else
    typealias Color = UIColor
#endif

Works for macOS, iOS, tvOS and watchOS. More on Swift's preprocessor directives.

Boehmenist answered 31/7, 2015 at 6:13 Comment(1)
Swift doesn't use flags like TARGET_OS_IPHONE. But it does have target-platform conditionals like #if os(iOS).Zollie
C
3

You can use a typedef within the preprocessor conditional:

#if TARGET_OS_IPHONE
typedef UIColor MONPlatformColor;
#elif
typedef NSColor MONPlatformColor;
#endif

And your API would be declared:

+ (MONPlatformColor *)makeMeColorful;
Cover answered 14/2, 2014 at 19:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.