本文介绍了我应该如何在Swift中替换这些屏幕尺寸和设备类型的宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

回到Objective-C,我在 constants.h 文件中定义了以下宏:

Back in Objective-C, I defined the following macros in a constants.h file:

#define IS_IPHONE5 (([[UIScreen mainScreen] bounds].size.height-568)?NO:YES)
#define IS_IPAD    (UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPad)
#define IS_IOS7 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7)
#define APP_DEFAULT_FONT_FACE @"HelveticaNeue-Light"
#define APP_DEFAULT_FONT_FACE_THIN @"HelveticaNeue-UltraLight"
#define APP_VERSION @"1.2"

我开始玩Swift,我注意到这些东西只是'不要'再工作了。那么现在我应该如何定义这些宏,并检测设备属于哪个系列?

I started playing with Swift and I noticed that these things just don't work anymore. So now how should I define these macros, and detect which family the device belongs to?

如果Swift没有宏,那么这样做的语法是什么?

And if Swift doesn't have macros, what is the syntax of doing it?

推荐答案

在这种情况下,定义这些常量的最简单方法似乎是使用 let 关键字。宏在Swift中不可用,因此在这种情况下你必须使用常量(在这种情况下,无论如何都可能在性能方面更好):

In this case, the easiest way to define these constants seems to be to use the let keyword. Macros are not available in Swift, so you have to use constants in this case (which may be better in terms of performance anyhow, in this case):

let IS_IPHONE5 = fabs(UIScreen.mainScreen().bounds.size.height-568) < 1;      
let IS_IPAD = (UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPad);
let IS_IOS8 = (UIDevice.currentDevice().systemVersion.floatValue >= 8)
let APP_DEFAULT_FONT_FACE_NAME = "HelveticaNeue-Light";
let APP_DEFAULT_FONT_FACE_THIN_NAME = "HelveticaNeue-UltraLight";
let APP_VERSION_STRING = "1.2";

IS_IPHONE5 常数,我用过 fabs 以避免可能的浮点舍入错误。我不确定它们是否会成为问题,但最好是安全...

for the IS_IPHONE5 constant, I used fabs to avoid possible floating point rounding errors. I'm not sure if they would be an issue, but it's better to be safe...

IS_IOS7 宏在Swift中没用,因为Swift ( IS_IOS7 总是 YES Swift程序。)我添加了一个 IS_IOS8 常量而不是......

The IS_IOS7 macro is useless in Swift, because Swift only supports iOS 7 and later versions (IS_IOS7 would always be YES in a Swift program.) I added an IS_IOS8 constant instead...

这篇关于我应该如何在Swift中替换这些屏幕尺寸和设备类型的宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 00:07