Swift和Objective-C的兼容相互兼容性使得在一個工程里可以方便地使用兩種語言,就這個使用場景,本文將介紹
- 如何將 Swift 導入到 Objective-C
- 如何將 Objective-C 導入到Swift
- 一個簡單的例子
- | 導入到Swift | 導入到Objective-C |
---|---|---|
Swift | 不需要import 語句 | #import "ProductModuleName-Swift.h" |
Objective-C | 不需要import 語句端三,需要Objective-C bridging 頭文件 | #import "header.h" |
一個簡單的例子
我們模擬一個項目,以前的控制器和工具類代碼都是用OC編寫蜕便,現(xiàn)在我們要用Swift編寫新的代碼溃斋,一般的,以前OC代碼會調用新編寫的Swift代碼分尸,Swift代碼也需要調用OC的工具類锦聊。
1. 設置Target>setting
將框架 target 的 Build Settings > Packaging > Defines Module 設置為 Yes
setting.png
2.新建Swift文件
在OC項目中第一次新建Swift文件時,系統(tǒng)會自動提示創(chuàng)建 Bridging 頭文件箩绍,如文章開頭表格所示孔庭,該文件用于將OC導入到Swift。
creatASwiftFile.png
3.將OC導入到Swift
我們用Swift寫了一個View材蛛,這個view被點擊時會掉用OC的工具類OCTools
的方法
1圆到、在SwiftAndOC-Bridging-Header.h
文件里#import "OCTools.h"
2、在Swfit文件里調用OCTools
的方法
import UIKit
class SwiftView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
initSubViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func initSubViews(){
self.backgroundColor = UIColor.lightGrayColor()
let dotView = UIView(frame: self.bounds)
dotView.center = self.center
dotView.layer.masksToBounds = true
dotView.layer.cornerRadius = self.bounds.size.height/2
dotView.layer.borderWidth = 1
dotView.layer.borderColor = UIColor.blackColor().CGColor
self.addSubview(dotView)
let tap = UITapGestureRecognizer(target: self, action: #selector(tapDotAction))
dotView.addGestureRecognizer(tap)
}
@objc private func tapDotAction(){
OCTools.logWithText("Don't touch me!")
}
}
3.將Swift導入到OC
我們用Swift編寫的view需要在OC寫的控制器里被調用
1卑吭、在控制器里#import "SwiftAndOC-swift.h"
芽淡,注意這里的頭文件時系統(tǒng)自動生成,格式是 "Your Product Name"-swift.h
2豆赏、調用Swift的類
#import "ViewController.h"
#import "SwiftAndOC-swift.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
SwiftView *sView = [[SwiftView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
sView.center = self.view.center;
[self.view addSubview:sView];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
For more information please visitUsing Swift with Cocoa and Objective-C:Swift and Objective-C in the Same Project