1、我们先创建一个OC的项目MyFirstOCUseSwiftDemo
2、我们点击Target看到右边选择Build Settings,把Defines Module改为YES,
3、我们回到工程目录下,New File一个Swift File,起名为MyFristSwift,此时会弹框提示我们是否创建一个桥接文件,如图:
4、创建好之后我们再次选择项目的Target看到右侧的Build Settings选项,往下滑动会看到这样一个目录:
此时是系统为我们自动创建了桥接"项目名-Swift"文件和"项目名-Bridging-Header"文件;
5、接下来我们开始创建自己的Swift文件,新建一个Swift起名为:MyFristSwift,它看起来应该长这样:
import Foundation
import UIKit
class MyFristSwift: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.green
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
6、接下来我们要在OC的控制器(也就是你想要调用Swift的OC控制器)里边import一下第四步图中展示的swift文件,此时注意的是这个头文件是手动写的,你也可以在第四步中复制Objcective-C Generated Interface Header Name对应的值;
7、好了,这是最后一步,在OC控制器中 创建一个按钮进入我们的swift页面吧,它应该是这样的:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
//创建属于我们自己的按钮
[self.view addSubview:self.nextBtn];
}
- (void)nextBtnClicked:(UIButton *)btn{
// 使用Swift的类
MyFristSwift *swiftVC = [[MyFristSwift alloc] init];
[self presentViewController:swiftVC animated:YES completion:nil];
}
-(UIButton *)nextBtn{
if (!_nextBtn) {
_nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
_nextBtn.frame = CGRectMake(40, 100, 100, 44);
_nextBtn.layer.masksToBounds = YES;
_nextBtn.layer.cornerRadius = 4;
_nextBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
[_nextBtn setTitle:@"进入Swift" forState:UIControlStateNormal];
[_nextBtn setBackgroundColor:[UIColor brownColor]];
[_nextBtn addTarget:self action:@selector(nextBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
}
return _nextBtn;
}