swift属性的未知类型名称

Nic*_*Yap 16 ios swift xcode6

我有一个用Swift编写的CustomViewController类和一个用Objective C编写的CustomNavigationController类.我正在尝试将CustomNavigationController作为属性添加到我的CustomViewController中.我已添加#import "CustomNavigationController.h"到我的桥接标题中.

在我的CustomViewController中,我有:

class CustomViewController: UIViewController {

    var navController: CustomNavigationController?
...
//init methods


...


 override func viewDidLoad() {
        super.viewDidLoad()

        //Set up Navigation Controller
        navController = self.storyboard.instantiateViewControllerWithIdentifier("CustomNavigationController") as CustomNavigationController!
}
Run Code Online (Sandbox Code Playgroud)

在我尝试构建和运行之前没有错误...我得到"未知类型名称'CustomNavigationController';你的意思是'UINavigationController'?"

有谁知道它为什么不识别这种类型?

mat*_*att 24

在Objective-C代码中,您可以导入自动生成的-Swift.h标头.在相同的代码中,#import之前插入#import "CustomNavigationController.h".这两个#import陈述的顺序至关重要!

这将通过确保CustomNavigationController在自动生成的-Swift.h标头之前位于命名空间中来解决问题,因此后者将了解前者并且一切都会很好.

如果Objective-C类不需要了解CustomNavigationController,这会让人感到烦恼,但它解决了前面的问题,并允许您继续使用混合项目.


joh*_*les 7

看起来ProjectName-Swift.h生成的头文件不会自动包含内容ProjectName-Bridging-Header.h.这会导致在导入之前尚未声明的任何类型在编译器中ProjectName-Swift.h抛出Unknown type name错误.这似乎是一个错误.

我的解决方法是创建ProjectName-Swift.h该转发的备用版本,声明导致错误的类,然后导入ProjectName-Swifth.h.我打电话给它ProjectName-Swift-Fixed.h.对我来说,ProjectName-Swift-Fixed.h看起来像这样:

// ProjectName-Swift-Fixed.h
@class CustomViewController;
#import "ProjectName-Swift.h"
Run Code Online (Sandbox Code Playgroud)

然后,在我所拥有的代码中的任何地方#include "ProjectName-Swift.h",我都用它代替了#include "ProjectName-Swift-Fixed.h"


小智 5

如果您无法#import按照上述答案的建议通过更改语句的顺序来解决问题,则检查文件中ProjectName-Bridging-Header.h是否缺少框架导入可能会起作用。

就我而言,我在桥接头文件中有一个类UIImage,它在其中一个方法中使用。当我的项目仅由运行良好的 Objective-C 组成时,当将此标头公开给 Swift 时,我必须添加#import <UIKit/UIKit.h>以消除错误。