1、在一个Swift工程里,我们添加一个OC文件,这个时候会弹出一个提示框。
你是否要配置一个OC的桥接头文件?
2、点击【Create Bridging Header】,会生成一个“工程名称-Bridging-Header.h”的文件
3、我们这里创建或者从外部添加了一个Objective C的类:OCUser类
OCUser.h
#import <Foundation/Foundation.h>
@interface OCUser : NSObject
@property (nonatomic, copy) NSString *userName; // 用户名
// 自我介绍
- (void)introduce;
@end
OCUser.m
#import "OCUser.h"
@implementation OCUser
- (void)introduce
{
NSLog(@"打印用户名:%@", self.userName);
}
@end
4、在SwiftDemo-Bridging-Header.h文件里引入OC头文件
//
// Use this file to import your target's public headers that you would like to expose to Swift.
//
#import "OCUser.h"
5、Swift文件里调用OC方法
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let user:OCUser = OCUser()
user.userName = "张三"
user.introduce()
}
}