当我在Objective-C中执行Swift方法时,该方法内部的代码不会运行。
例如:我想打开一个新视图或启用一个按钮。
Principal *myClass = [[Principal alloc] init];
[myClass getData];
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)
})
}
答案 0 :(得分: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
这里的秘密是在这种情况下使用“-Swift.h”扩展名导入目标名称“TestProject”。 Xcode为您构建了这个并将其隐藏在派生数据的幕后。对于上面的例子,我的遗留在:DerivedData / TestProject-aqpeqeuqusyzdtcqddjdixoppyqn / Build / Intermediates / TestProject.build / Debug-iphoneos / TestProject.build / DerivedSources / TestProject-Swift.h
答案 1 :(得分:0)