您如何为当前平台使用适当的颜色类? [英] How do you use the appropriate color class for the current platform?

查看:25
本文介绍了您如何为当前平台使用适当的颜色类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试跨 iOS 和 OS X 共享我的 Scene Kit 代码,但接受颜色(和图像)的 API 调用根据平台采用 UIColor/UIImage 或 NSColor/NSImage.如何在不重复代码的情况下在 Swift 中创建正确的类?

I'm trying to share my Scene Kit code across iOS and OS X, but the API calls that accept colors (and images) take either UIColor/UIImage or NSColor/NSImage depending on the platform. How do I create the right class in Swift without duplicating the code?

推荐答案

使用条件编译和类型别名:

Use conditional compilation and type aliases:

#if os(OSX)
    typealias Color = NSColor
    typealias Image = NSImage
#else
    typealias Color = UIColor
    typealias Image = UIImage
#endif

然后使用 Color 而不是 UIColor 或 NSColor:

Then use Color instead of UIColor or NSColor:

self.gameView!.backgroundColor = Color(red: 0, green: 0.2, blue: 0.5, alpha: 1)

<小时>

编辑 2016-01-17:正如上面提到的 DDPWNAGE,Apple 已经创建了 SKColor 定义基本相同.


Edit 2016-01-17: As DDPWNAGE noted above, Apple has created SKColor with basically the same definition.

这篇关于您如何为当前平台使用适当的颜色类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆