项目中 OC 和 Swift 的类来回跳转,桥接问题
我们知道Swift中自定义的类不需要导入头文件,编译器会自动帮我们导入。那么Objective-C怎么做呢?
跟着网上教程,当我们创建以Swift为语言的工程后,在第一次创建或拖入OC语言的文件时会自动弹出一个对话框,如下:
该提示的意思是,是否创建一个Objective-C bridging header,也就是创建一个Swift中能调到OC的桥文件。我们点击回车,会自动创建一个名叫 你的项目名(默认)-Bridging-Header.h 的头文件。这文件是干什么用的呢?
我们点开这个文件,里面只有这样一行注释:
以我不怎么样的英语造诣,直译如下:
使用这个文件来导入你想导入到Swift中的(OC)目标头文件.h。
简单明了。接下来怎么做?
直接在这个文件中导入头文件,之后你可以在Swift语言中直接使用,就像Swift类一样。
导入头文件:
//
// Use this file to import your target's public headers that you would like to expose to Swift.
//
#import "BoxHomeViewController.h"
然后就可以在swift里面调用oc的类了,如
let vc = BoxHomeViewController()
self.navigationController?.pushViewController(vc, animated: true)
在 OC 类 里面调用Swift,也不难
首先,我们需要到Target - - Build Settings--Packging--Defines Module,将值改为YES。
然后,我们到所想要调用Swift类的OC类中,调用这样一个头文件:
#import <你的项目名-Swift.h>
若你没有修改,一般都是你的项目名。你可能会想,我并没有创建这样一个头文件。但是要仔细看,它使用的是尖括号<>,这说明它是系统类,你是看不到的。
如 :
#import "BoxHomeViewController.h"
#import <BoxSwiftDemo-Swift.h>
@interface BoxHomeViewController ()
@end
@implementation BoxHomeViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor lightGrayColor];
self.navigationItem.title = @"OC的类";
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];;
button.frame = CGRectMake(50, 150, 100, 50);
button.backgroundColor = [UIColor greenColor];
[button setTitle:@"去Swift类看看" forState:UIControlStateNormal];
[button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
#pragma mark - 跳往swift方法
- (void)buttonClick {
// 这里 SecondViewController.swift 是swift文件
SecondViewController *second = [[SecondViewController alloc] init];
[self.navigationController pushViewController:second animated:YES];
}