【发布时间】:2016-04-25 03:41:12
【问题描述】:
我有一个 swift 项目,我在项目中导入了一个单例、objective-c 编码的类。
我尝试导入 productname_swift.h 文件,但没有成功。
我如何访问那个单例类中的 swift 类?
【问题讨论】:
-
答案已更新为在 Objective C 中使用 swift 类。
标签: ios objective-c iphone swift swift2
我有一个 swift 项目,我在项目中导入了一个单例、objective-c 编码的类。
我尝试导入 productname_swift.h 文件,但没有成功。
我如何访问那个单例类中的 swift 类?
【问题讨论】:
标签: ios objective-c iphone swift swift2
用 Swift 制作的项目:在 Objective C 中使用 Swift 类
要在 Objective C 中使用 Swift 类,请按照给定的步骤操作:
User.h
#import <Foundation/Foundation.h>
@interface User : NSObject
+(id) sharedUser ;
@end
User.m
#import "User.h"
#import "SwiftInObjectiveC-swift.h"
@implementation User
//Singleton of User
+(id)sharedUser{
static User *sharedUser = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedUser = [[self alloc] init];
//Class Method of ViewController.swift
[ViewController mySwiftClassFunction];
//Instance Method of ViewController.swift
ViewController *vc = [[ViewController alloc] init];
[vc mySwiftFunction];
});
return sharedUser;
}
-(void) myObjcectivecMethod {
ViewController *vc = [[ViewController alloc] init];
[vc mySwiftFunction];
}
在您的 .swift 类中的类名前面添加 @objc。
import UIKit
@objc class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func mySwiftFunction() {
print("Swift Function")
}
class func mySwiftClassFunction (){
print("Swift Class Function")
}
}
转到构建设置。
设置产品模块名称:项目名称
关注Mix and Match 的 Apple 链接了解详细信息。
【讨论】:
将多个 Swift 文件添加到一个 Objective-C 项目中。
假设您想将 Class1.swift、Class2.swift 和 Class3.swift 文件添加到 SwiftToObjC 项目
@class Class1;
@class Class1;
@class Class2;
@class Class3;
5. 在目标 SwiftToObjC 中,在 Build Settings 下,Swift-Compiler General 你应该看到这两个设置:
Objective-C 桥接头 -> SwiftToObjC-Bridging-Header.h
Objective-C 生成的接口头名称 -> SwiftToObjC-Swift.h
6. 在目标SwiftToObjC中,在Build Settings下,Define Module设置为YES。
#import "SwiftToObjC-Bridging-Header.h"
@objc 公共类 Class1: UITableViewController
注意:UITableViewController 只是一个示例,用于演示目的。
就是这样。
【讨论】: