在Swift中使用Objective-C类的正确方法是什么?

sev*_*low 17 swift xcode6

我正试图将一些类别方法导入到我的Swift文件中而没有任何运气.

IOS桥接-Header.h:

#import "UIColor+Hex.h"
Run Code Online (Sandbox Code Playgroud)

的UIColor + Hex.h

#import <UIKit/UIKit.h>

@interface UIColor (Hex)

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

@end
Run Code Online (Sandbox Code Playgroud)

我希望自动完成能够显示UIColor(hexInt: NSUInteger)UIColor(hexString: String)

aka*_*kyy 32

实际上,您的类别已转换为Swift,如下所示:

extension UIColor {

    init(hex hexInt: Int) -> UIColor

    init(hexString: String) -> UIColor

}
Run Code Online (Sandbox Code Playgroud)

因此,你应该使用:

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

let color = UIColor(hexString: "ffffff")
Run Code Online (Sandbox Code Playgroud)

不过,测试版软件中的自动完成功能可能仍然存在问题.

  • 3年后......自动完成仍然是错误的. (3认同)

Dan*_*ark 24

您可以直接在Swift中使用Objective-C类别.这对于某些桥接类(如String)非常有趣.使用Objective-C中的类别扩展NSString,然后可以从Swift访问它(直接在String上!)

这样做的方法是在Swift项目中创建一个"桥接头".

这里有完整说明.

缺点是:

  1. 使用其中的所有其他#import语句创建一个.h头文件(在Objective-C中)
  2. 将该文件的路径放入Objective-C Bridging HeaderBuild Settings中
  3. 无需在Swift文件中导入桥接头.它已经存在了