【问题标题】:Execute swift code in Objective-C在 Objective-C 中执行 swift 代码
【发布时间】:2015-12-22 11:52:25
【问题描述】:

当我在 Objective-C 中执行 Swift 方法时,该方法内部的代码不会运行。

例如:我想打开一个新视图或启用一个按钮。

Objective-C 代码:

Principal *myClass = [[Principal alloc] init];
[myClass getData];

Swift 代码:

func getData() {
    let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let vc: UIViewController = storyboard.instantiateViewControllerWithIdentifier("MenuViewController") as UIViewController
    dispatch_async(dispatch_get_main_queue(), {
        self.presentViewController(vc, animated: true, completion: nil)
    })
}

【问题讨论】:

标签: objective-c swift ios9


【解决方案1】:

确保您使用 @objc 关键字来标记您的 Swift 类,以便您的 ObjC 类可以使用它们。

import Foundation

@objc class TestClass {
class func new() -> TestClass {
    return TestClass()
}

func testFunction() {
    println("This function works")
}
}

这是 Objective-C 客户端:

#import "AppDelegate.h"
#import "TestProject-Swift.h"
@implementation AppDelegate
 - (BOOL)application:(UIApplication *)application 
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    TestClass *instance = [TestClass new];
    [instance testFunction];
    return YES;
}
@end

这里的秘诀是在这种情况下导入目标名称“TestProject”和“-Swift.h”扩展名。 Xcode 为您构建了这个并将其隐藏在派生数据的幕后。对于上面的例子,我的留在:DerivedData/TestProject-aqpeqeuqusyzdtcqddjdixoppyqn/Build/Intermediates/TestProject.build/Debug-iphoneos/TestProject.build/DerivedSources/TestProject-Swift.h

【讨论】:

    【解决方案2】:

    您需要在您的项目中创建一个头文件(.h 文件)并导入您需要的所有类。

    你的头文件看起来像。

    #ifndef ProjectName_Bridging_Header_h
    #define ProjectName_Bridging_Header_h
    
    #import "Principal.h"
    

    在您的构建设置中,您需要将头文件名设置为Objective-C Bridging Header

    像这样。

    【讨论】:

    • 这不是为了在 inside Swift 中运行 Objective-C 吗?他想在 Objective-C 中运行 Swift(正好相反),还是我错了?
    • 是的,我想在 Objective-C 中调用 Swift 函数。
    • 确保你使用 @objc 关键字来标记你的 Swift 类,以便你的 ObjC 类可以使用它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多