2014-02-14 30 views
8

我試圖做一個NSObject子類,它將有很多返回顏色的方法,所以我想要返回UIColor如果我爲iOS構建或NSColor如果我正在構建爲OS X
這是一種預期行爲應該是什麼樣的僞代碼:
如何在NSColor和UIColor之間自動選擇正確的構建系統? (使用#define,或者其他)

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

+ (COLOR *)makeMeColorful; 

是否有可能做這樣的事情,而不是使2種方法對我的每一個對象的方法(一個用於iOS,另一個用於OS X)?

+1

請參閱http://stackoverflow.com/questions/15323109/creating-an-ios-os-x-cross-platform-class?rq=1 – rmaddy

回答

13

這是絕對可行的。 SKColor從SpriteKit例如,定義,如:

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

然後利用這樣的:

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

這只是發生的事實的優點UIColorNSColor分享一些自己的類方法。

+1

非常聰明的蘋果。 ;) – SevenBits

+2

這正是我正在尋找的,謝謝你,先生! –

+1

注意'NSColor'和'UIColor'不共享*所有*他們的API,所以你必須小心,不要調用只存在於其中一個或另一個的方法。 – rickster

2

您可以在預處理器條件內使用typedef

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

而且你的API會宣佈:

+ (MONPlatformColor *)makeMeColorful; 
5

如果您使用的斯威夫特嘗試在

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

適用於macOS,iOS,tvOS和watchOS。更多關於Swift's preprocessor directives

+0

Swift不使用像'TARGET_OS_IPHONE'這樣的標誌。但它確實有[目標平臺條件](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithCAPIs.html#//apple_ref/doc/uid/TP40014216-CH8 -ID31)像'#if os(iOS)'。 – rickster

+0

感謝您指出這一點! – fpg1503

相關問題