简体   繁体   English

如何在另一个Swift类中访问常量值

[英]How to access constants value in another swift class

how to get constant #define value in swift class. 如何在Swift类中获取恒定的#define值。 I have created constant.h class in my project, here I created the screen width and hight two constants values. 我在项目中创建了constant.h类,在这里我创建了屏幕宽度和高两个常数值。

Constant.h 常数h

#define SCREEN_WIDTH_SWIFT          UIScreen.main.bounds.size.width
#define SCREEN_HEIGHT_SWIFT         UIScreen.main.bounds.size.height

Now i want to asses SCREEN_HEIGHT_SWIFT in ViewController.swift class 现在我想在ViewController.swift类中评估SCREEN_HEIGHT_SWIFT

NSFontAttributeName : UIFont(name: "GillSans-Light" , size: MS_SCREEN_HEIGHT_SWIFT/40.5)!,NSForegroundColorAttributeName : UIColor.white

#define creates a C style compiler macro, not a constant. #define创建C风格的编译器宏,而不是常量。 Swift doesn't support C compiler macros. Swift不支持C编译器宏。 You will need to use an actual constant. 您将需要使用实际常数。

Hi instead of using #define use let and assign the values with a = : 您好,而不是使用#define而是使用let并使用=赋值:

let SCREEN_WIDTH_SWIFT = UIScreen.main.bounds.size.width
let SCREEN_HEIGHT_SWIFT = UIScreen.main.bounds.size.height

Simply create separate class to maintain your all constants. 只需创建单独的类即可维护您的所有常量。 Lets say AppConstats is your class. 可以说AppConstats是您的课程。 Then create your constants like this: 然后像这样创建常量:

static let SCREEN_WIDTH = UIScreen.main.bounds.size.width

Now wherever you want to access your constant, simply use like this: 现在,只要您想访问常量,就可以像这样使用:

AppConstats.SCREEN_WIDTH

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM