use*_*613 5 iphone objective-c ios swift swift2
我有一个 swift 项目,我在项目中导入了一个单例、objective-c 编码的类。
我尝试导入 productname_swift.h 文件,但没有成功。
我如何访问该单例类中的 swift 类?
用 Swift 制作的项目:在 Objective C 中使用 Swift 类
要在 Objective C 中使用Swift 类,请按照给定的步骤操作:
用户.h
#import <Foundation/Foundation.h>
@interface User : NSObject
+(id) sharedUser ;
@end
Run Code Online (Sandbox Code Playgroud)
用户.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];
}
Run Code Online (Sandbox Code Playgroud)
@objc在类名前面添加您的 .swift 类。
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")
}
}
Run Code Online (Sandbox Code Playgroud)转到构建设置。
设置产品模块名称:ProjectName
请关注 Apple 的Mix and Match链接,了解详细信息。
| 归档时间: |
|
| 查看次数: |
5585 次 |
| 最近记录: |