一、需求背景
实际开发中要用到一个第三方库,第三方库是用Swift写的,而自己项目的代码是OC写的,所以需要OC和Swift混合编程。
二、OC调用Swift
1、当在OC项目中新建第一个Swift文件时,会提示是否要创建桥接文件,
一般选是,这样省去了自己创建桥接文件的步骤。
2.1、OC的代码中需要调用Swift的文件,需要导入隐式头文件:xxx-Swift.h,xxx-Swift.h在项目中是看不到的,但是确实是可以import的。
2.2、新建Swift类,RCTestController类
import UIKit
class RCTestController: UIViewController {
override func viewDidLoad() {
self.view.backgroundColor = UIColor.yellow
NSLog("我是Swift")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let vc = ViewController.init()
vc.ocTest(withStr: "我是Swift")
self.navigationController?.pushViewController(vc, animated: true)
}
}
2.3、OC调用Swift类
RCTestController *vc = [[RCTestController alloc] init];
[self.navigationController pushViewController:vc animated:YES];
2.4、OC调用Swift类的方法,要在Swift类前面加@objcMembers
修饰符,不然会有问题。
import UIKit
@objcMembers class RCTestController: UIViewController {
override func viewDidLoad() {
self.view.backgroundColor = UIColor.yellow
NSLog("我是Swift")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let vc = ViewController.init()
vc.ocTest(withStr: "我是Swift")
self.navigationController?.pushViewController(vc, animated: true)
}
func testSwiftFunc(str: String) {
NSLog("OC传的字符串是::\(str)")
}
}
OC中调用
RCTestController *vc = [[RCTestController alloc] init];
[vc testSwiftFuncWithStr:@"我是OC"];
[self.navigationController pushViewController:vc animated:YES];
三、Swift调用OC
1、在xxx-Bridging-Header.h
的桥接文件中导入要开放的OC类
//
// Use this file to import your target's public headers that you would like to expose to Swift.
//
#import "ViewController.h"
2、Swift直接调用*
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let vc = ViewController.init()
vc.ocTest(withStr: "我是Swift")
self.navigationController?.pushViewController(vc, animated: true)
}
网友评论