What's the proper way to use an Objective-C ca

2019-01-14 22:23发布

问题:

I'm trying to import some category methods into my Swift file without any luck.

ios-Bridging-Header.h:

#import "UIColor+Hex.h"

UIColor+Hex.h

#import <UIKit/UIKit.h>

@interface UIColor (Hex)

+ (UIColor *)colorWithHex:(NSUInteger)hexInt;
+ (UIColor *)colorWithHexString:(NSString *)hexString;

@end

I would expect the autocomplete to reveal UIColor(hexInt: NSUInteger) and UIColor(hexString: String)

回答1:

Actually, your category is transtlated to Swift as follows:

extension UIColor {

    init(hex hexInt: Int) -> UIColor

    init(hexString: String) -> UIColor

}

And because of that, you should be using:

let color = UIColor(hex: 0xffffff) // instead of hexInt:

let color = UIColor(hexString: "ffffff")

Autocompletion may still be buggy in the beta software, though.



回答2:

You can use Objective-C categories directly in Swift. This gets really interesting for some of the bridged classes, like String. Extend NSString with a category in Objective-C, and then you can access it from Swift (directly on String!)

The way to do this is by creating a "bridging header" in your Swift project.

Full instructions here.

The short of it is:

  1. Make a .h header file (in Objective-C) with all the other #import statements in it
  2. Put the path to that file in Objective-C Bridging Header in your Build Settings
  3. No need to import the bridging header in your Swift file. It's already there


标签: swift xcode6