How to use Objective-C code with #define macros in

2019-01-11 22:24发布

I'm trying to use a third-party Objective-C library in a Swift project of mine. I have the library successfully imported into Xcode, and I've made a <Project>-Bridging-Header.h file that's allowing me to use my Objective-C classes in Swift.

I seem to be running into one issue however: the Objective-C code includes a Constants.h file with the macro #define AD_SIZE CGSizeMake(320, 50). Importing Constants.h into my <Project>-Bridging-Header.h doesn't result in a global constant AD_SIZE that my Swift app can use.

I did some research and saw that the Apple documentation here under "Complex Macros" says that

“In Swift, you can use functions and generics to achieve the same results [as complex macros] without any compromises. Therefore, the complex macros that are in C and Objective-C source files are not made available to your Swift code.”

After reading that, I got it to work fine by specifying let AD_SIZE = CGSizeMake(320, 50) in Swift, but I want to maintain future compatibility with the library in the event that these values change without me knowing.

Is there an easy fix for this in Swift or my bridging header? If not, is there a way to replace the #define AD_SIZE CGSizeMake(320, 50) in Constants.h and keep things backwards-compatible with any existing Objective-C apps that use the old AD_SIZE macro?

3条回答
冷血范
2楼-- · 2019-01-11 22:32

write your constants after Class declaration. like this...

class ForgotPasswrdViewController: UIViewController {
let IS_IPHONE5 = fabs(UIScreen.mainScreen().bounds.size.height-568) < 1;
let Tag_iamTxtf = 101
查看更多
霸刀☆藐视天下
3楼-- · 2019-01-11 22:35

What I did is to create a class method that returns the #define.

Example:

.h file:

#define AD_SIZE CGSizeMake(320, 50)
+ (CGSize)adSize;

.m file:

+ (CGSize)adSize { return AD_SIZE; }

And in Swift:

Since this is a class method you can now use it almost as you would the #define. If you change your #define macro - it will be reflected in the new method you created In Swift:

let size = YourClass.adSize()

查看更多
再贱就再见
4楼-- · 2019-01-11 22:49

I resolved this by replacing

#define AD_SIZE CGSizeMake(320, 50)

in the library's Constants.h with

extern CGSize const AD_SIZE;

and adding

CGSize const AD_SIZE = { .width = 320.0f, .height = 50.0f };

in the library's Constants.m file.

查看更多
登录 后发表回答