如何从Swift确定设备类型? (OS X或iOS) [英] How to determine device type from Swift? (OS X or iOS)

查看:335
本文介绍了如何从Swift确定设备类型? (OS X或iOS)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Swift相对较新,但是我想知道是否有确定设备类型的方法?

I know Swift is relatively new, but I was wondering if there was a way to determine the device type?

(就像您以前可以使用#define一样)?

(Like you used to be able to do with a #define)?

主要我想知道如何区分OS X或iOS.在这个问题上我什么都没找到.

Mainly I would like to know how to differentiate OS X or iOS. I have found nothing on the subject.

推荐答案

如果要同时为iOS和OS X进行构建(也许现在也为watchOS和tvOS进行构建),则至少要两次构建代码:每个平台一次.如果要在每个平台上执行不同的代码,则需要构建时有条件的检查,而不是运行时检查.

If you're building for both iOS and OS X (and maybe now for watchOS and tvOS, too), you're building your code at least twice: once for each platform. If you want different code to execute on each platform, you want a build-time conditional, not a run-time check.

Swift没有预处理器,但是它确实有条件的构建指令-在大多数情况下,它们看起来像C等效语言.

Swift has no preprocessor, but it does have conditional build directives — and for the most part, they look like the C equivalent.

#if os(iOS) || os(watchOS) || os(tvOS)
    let color = UIColor.redColor()
#elseif os(OSX)
    let color = NSColor.redColor()
#else
    println("OMG, it's that mythical new Apple product!!!")
#endif

您还可以使用构建配置来测试体系结构(x86_64armarm64i386)或-D编译器标志(包括由标准Xcode模板定义的DEBUG标志)

You can also use build configurations to test for architecture (x86_64, arm, arm64, i386) or -D compiler flags (including the DEBUG flag defined by the standard Xcode templates).

请参见((如果您想区分运行时使用的是哪种iOS设备,请像使用ObjC一样使用UIDevice类.通常,查看对您而不是设备名称或习惯用语-例如,使用特征和大小类来布置用户界面,向OpenGL查询所需的GPU功能,等等.

(If you want to distinguish which kind of iOS device you're on at runtime, use the UIDevice class just like you would from ObjC. It's typically more useful and safe to look at the device attributes that are important to you rather than a device name or idiom — e.g. use traits and size classes to lay out your UI, query OpenGL for the GPU capabilities you require, etc.)

这篇关于如何从Swift确定设备类型? (OS X或iOS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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