如何从Swift中确定设备types? (OS X或iOS)

我知道斯威夫特是相对较新的,但我想知道是否有一种方法来确定设备types?

(就像你以前能用#define做的那样)?

主要我想知道如何区分OS X或iOS。 我没有发现这个问题。

如果您正在为iOS和OS X(也许现在也用于watchOS和tvOS)构build代码,那么您至less要构build两次代码:每个平台一次。 如果你想要在每个平台上执行不同的代码,你需要一个构build时有条件的,而不是运行时检查。

Swift没有预处理器,但它确实有条件构build指令 – 而且大多数情况下,它们看起来就像C等价物。

 #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 

您还可以使用构buildconfiguration来testing架构( x86_64armarm64i386 )或-D编译器标志(包括由标准Xcode模板定义的DEBUG标志)。

请参阅使用Cocoa和Objective-C中的Swift中的 预处理器指令 。

(如果你想区分你在运行时使用的是哪一种iOS设备,可以像使用ObjC一样使用UIDevice类,通常更加有用和安全的方法是查看对你来说比较重要的设备属性,而不是设备名称或成语 – 例如使用特质和大小类来布局你的用户界面,查询你需要的GPUfunction的OpenGL等)

我已经实现了一个超轻量级库来检测使用的设备 : https : //github.com/schickling/Device.swift

它可以通过迦太基安装和使用是这样的:

 import Device let deviceType = UIDevice.currentDevice().deviceType switch deviceType { case .IPhone6: print("Do stuff for iPhone6") case .IPadMini: print("Do stuff for iPad mini") default: print("Check other available cases of DeviceType") } 
 var device = UIDevice.currentDevice().model 

此代码为我工作。 我已经在textfield和keyboard dismissing部分实现了。 见下文。

 func textFieldShouldBeginEditing(textField: UITextField) -> Bool { print(device) if (textField.tag == 1 && (device == "iPhone" || device == "iPhone Simulator" )) { var scrollPoint:CGPoint = CGPointMake(0,passwordTF.frame.origin.y/2); LoginScroll!.setContentOffset(scrollPoint, animated: true); } else if (textField.tag == 2 && (device == "iPhone" || device == "iPhone Simulator")) { var scrollPoint:CGPoint = CGPointMake(0,passwordTF.frame.origin.y/1.3); LoginScroll!.setContentOffset(scrollPoint, animated: true); } return true }