【问题标题】:Inheritance from an Objective-c base view controller from Swift从 Swift 的 Objective-c 基础视图控制器继承
【发布时间】:2014-06-20 13:17:53
【问题描述】:

我正在尝试将 UIViewController Objective-C 类迁移到 Swift。此视图控制器继承自 BaseViewController,在该 BaseViewController 中,我拥有我希望在所有控制器中拥有的通用功能。我遇到的问题是生成的myproject-Swift.h 无法找到我的BaseViewController

有什么方法可以在 swift 中实现一个 UIViewController,它继承自用 Objective-C 编写的 BaseViewControllerUIViewController 的子类)?是否存在桥接问题?

可以用这个最少的代码复制它:

BaseViewController.h

#import <UIKit/UIKit.h>

@interface BaseViewController : UIViewController 
@end

BaseViewController.m

import "BaseViewController.h"

@implementation BaseViewController
@end

ViewController.swift

import UIKit

class ViewController : BaseViewController {

}

AppDelegate.m

#import "AppDelegate.h"
#import "projectname-Swift.h"   // Replace with your project name

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    ViewController *vc = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
    self.window.rootViewController = vc;
    [self.window makeKeyAndVisible];

    return YES;
}

项目名称-Bridging-Header.h

#import "BaseViewController.h"

【问题讨论】:

  • 你的 objc 桥接头是什么样的?
  • @NateCook 已更新。这很简单。
  • 仅仅有一个桥接头是不够的,它设置正确吗?见stackoverflow.com/questions/24272184/…
  • @JackWu 我想是的。标头包含在“Objective-C Bridging Header”中。
  • 有趣。看起来您拥有正确格式和位置的所有必需部件。 ...也许是一个愚蠢的问题,但您是否真的构建/运行了该项目?这是生成的 .swift 标头所必需的。在 WWDC“与 Objective-C 集成”视频中的某处也提到了使用 @class 前向声明,但我不记得具体细节...

标签: ios objective-c uiviewcontroller swift


【解决方案1】:

正如在How can I add forward class references used in the -Swift.h header? 上接受的答案中指出的那样

Interoperability guide(将 Swift 导入 Objective-C):

如果您在 Swift 代码中使用自己的 Objective-C 类型,请确保 在导入之前导入这些类型的 Objective-C 标头 Swift 生成的标头到您要访问的 Objective-C .m 文件中 Swift 代码来自。

该示例通过在导入projectname-Swift.h之前导入BaseViewController解决:

AppDelegate.m

#import "AppDelegate.h"
#import "BaseViewController.h"
#import "projectname-Swift.h"   // Replace with your project name
// ...

【讨论】:

    【解决方案2】:

    看起来他们已经解决了这个问题。目前在 XCode6-Beta6 下,@atxe 报告的问题不再发生。因此,您最终可以将 AppDelegate.m 标头回滚到:

    #import "AppDelegate.h"
    #import "projectname-Swift.h"   // Replace with your project name
    

    【讨论】:

      猜你喜欢
      • 2014-01-26
      • 2018-04-22
      • 1970-01-01
      • 1970-01-01
      • 2016-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多