Swift - 17.Objective-C与Swift混编

本章包含内容:

  • 需求描述
  • Objective-C调用Swift
  • Swift调用Objective-C

在Objective-C中混编C++是老生常谈。C++执行效率快,且拥有良好的跨平台性,在很多时候我们需要在我们的OC代码中混编c++。
在OC中混编C++是无缝对接,只需要把.m文件改为.mm即可,在这里不做重点讲述。
2014年苹果在开发者发布会中,推出了Swift,Swift的优异和缺点在这里不做细述。
在经过swift前几个版本的沉淀,到现在的swift3,swift也逐渐成熟。
听说2017年秋季,苹果将推出4.0版本,该版本提供后台API,开源的语言就是牛逼啊~~~~
作为一个苹果码农,坚决不能停下学习的脚步,时刻保持最佳状态。
好了,废话有点多,进入正题,我就说一句,只会Objective-C的苹果开发者要混不下去了。so,我们这里要做的是敲开Objective-C与Swift的壁垒。

一、Objective-C调用Swift

1.创建一个Objective-C工程,如下图:

Swift - 17.Objective-C与Swift混编_第1张图片
Objective-C工程

2.在AppDelegate添加以下代码:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    ViewController * vc = [[ViewController alloc] init];
    UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:vc];
    self.window.rootViewController = nav;
    
    return YES;
}

3.创建一个swift文件,此时会提示是否创建桥接文件,我们选择Create Bridging Header如下:

Swift - 17.Objective-C与Swift混编_第2张图片
创建Swift文件的同时,创建桥接头文件

此时,工程中会有一个XXX-Bridging-Header.h文件,其中XXX是工程名。此时我们在该文件中 #import "xxx.h"则可以在Swift中调用OC方法,此时的xxx为OC类名。

另外,工程中也添加了一个隐藏的XXX-Swift.h文件,此时我们在需要调用Swift方法的文件里#import "XXX-Swift.h"即可调用Swift方法,其中XXX为工程名。

如果我们想把XXX-Swift.h的XXX修改为自己想要的名称可以通过一下方式修改自定义的名称:
TARGETS->Build Settings -> Packaging -> Product Name

Swift - 17.Objective-C与Swift混编_第3张图片
修改XXX-Swift.h命名

下面是实现代码:

ViewController.m文件中添加一下代码


#import "ViewController.h"
#import "OcAndSwiftDemo-Swift.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor redColor];
    self.title = @"OC Controller";
    
    [self createBtn];
    
}

//创建按钮,测试OC调用Swift方法
- (void)createBtn{
    UIButton * btn = [[UIButton alloc] initWithFrame:CGRectMake(([UIScreen mainScreen].bounds.size.width - 300)*0.5, 80, 300, 50)];
    [btn setTitle:@"调用swift多参方法" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(func1) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
    UIButton * btn2 = [[UIButton alloc] initWithFrame:CGRectMake(([UIScreen mainScreen].bounds.size.width - 300)*0.5, 140, 300, 50)];
    [btn2 setTitle:@"调用swift含有返回值方法" forState:UIControlStateNormal];
    [btn2 addTarget:self action:@selector(func2) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn2];
    
    UIButton * btn3 = [[UIButton alloc] initWithFrame:CGRectMake(([UIScreen mainScreen].bounds.size.width - 300)*0.5, 200, 300, 50)];
    [btn3 setTitle:@"调用swift静态方法" forState:UIControlStateNormal];
    [btn3 addTarget:self action:@selector(func3) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn3];
    
}

#pragma mark - 调用Swift方法
- (void)func1{
    SwiftController * swiftVC = [[SwiftController alloc] init];
    [swiftVC swiftFunc1WithPar1:@"OC调用" par2:@"Swift多参方法"];
}

- (void)func2{
    SwiftController * swiftVC = [[SwiftController alloc] init];
    NSLog(@"%@",[swiftVC swiftFunc2WithPar:@"OC调用Swift含有返回值方法"]);
}

- (void)func3{
    [SwiftController swiftFuncStaticWithPar:@"OC调用Swift静态方法"];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
SwiftController.swift文件中添加一下代码

import UIKit

class SwiftController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.blue;
        self.title = "Swift Controller"
    }
    
    //1.带参数的swift方法
    func swiftFunc1(par1: String, par2: String) {
        print(par1 + par2)
    }
    
    //2.带返回值的swfit方法
    func swiftFunc2(par: String) -> String {
        return par;
    }
    
    //3.swift静态方法
    static func swiftFuncStatic(par: String) {
        print(par)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }

}

到这里,我们实现了在OC中调用Swift

二、Swift调用Objective-C

Swift调用OC,在上面我们已经知道只需要在XXX-Bridging-Header.h中import我们需要的类,就可以在Swift中调用OC方法。

1.我们在ViewController.h中公开OC方法

#import 

@interface ViewController : UIViewController

//公开的OC方法,待Swift调用
- (void)ocMethod1Par1:(NSString *)par1 par2:(NSString *)par2;
- (NSString *)ocMethod2Par:(NSString *)par;
+ (void)ocStaticMethodPar:(NSString *)par;

@end

2.我们在ViewController.m中实现OC方法


#import "ViewController.h"
#import "OcAndSwiftDemo-Swift.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor redColor];
    self.title = @"OC Controller";
    
    [self createBtn];
    
}

//创建按钮,测试OC调用Swift方法
- (void)createBtn{
    UIButton * btn = [[UIButton alloc] initWithFrame:CGRectMake(([UIScreen mainScreen].bounds.size.width - 300)*0.5, 80, 300, 50)];
    [btn setTitle:@"调用swift多参方法" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(func1) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
    UIButton * btn2 = [[UIButton alloc] initWithFrame:CGRectMake(([UIScreen mainScreen].bounds.size.width - 300)*0.5, 140, 300, 50)];
    [btn2 setTitle:@"调用swift含有返回值方法" forState:UIControlStateNormal];
    [btn2 addTarget:self action:@selector(func2) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn2];
    
    UIButton * btn3 = [[UIButton alloc] initWithFrame:CGRectMake(([UIScreen mainScreen].bounds.size.width - 300)*0.5, 200, 300, 50)];
    [btn3 setTitle:@"调用swift静态方法" forState:UIControlStateNormal];
    [btn3 addTarget:self action:@selector(func3) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn3];
    
    UIButton * push = [[UIButton alloc] initWithFrame:CGRectMake(100, 300, 150, 50)];
    [push setTitle:@"push" forState:UIControlStateNormal];
    [push addTarget:self action:@selector(pushClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:push];
}

#pragma mark - 调用Swift方法
- (void)func1{
    SwiftController * swiftVC = [[SwiftController alloc] init];
    [swiftVC swiftFunc1WithPar1:@"OC调用" par2:@"Swift多参方法"];
}

- (void)func2{
    SwiftController * swiftVC = [[SwiftController alloc] init];
    NSLog(@"%@",[swiftVC swiftFunc2WithPar:@"OC调用Swift含有返回值方法"]);
}

- (void)func3{
    [SwiftController swiftFuncStaticWithPar:@"OC调用Swift静态方法"];
}

#pragma mark - push 到 Swift 控制器
- (void)pushClick{
    SwiftController * swiftVC = [[SwiftController alloc] init];
    [self.navigationController pushViewController:swiftVC animated:YES];
}

#pragma mark - OC方法,在Swift文件中被调用
- (void)ocMethod1Par1:(NSString *)par1 par2:(NSString *)par2{
    NSLog(@"%@%@",par1,par2);
}

- (NSString *)ocMethod2Par:(NSString *)par{
    return par;
}

+ (void)ocStaticMethodPar:(NSString *)par{
    NSLog(@"%@", par);
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

3.在XXX-Bridging-Header.himport我们需要的类

#import "ViewController.h"

4.在Swift中调用OC方法


import UIKit

class SwiftController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.blue;
        self.title = "Swift Controller"
        
        let btn = UIButton(frame: CGRect(x: (UIScreen.main.bounds.size.width - 200)*0.5, y: 100, width: 200, height: 50));
        btn.setTitle("调用OC多参方法", for: .normal)
        btn.addTarget(self, action: #selector(funcClick1), for: .touchUpInside)
        self.view.addSubview(btn)
        
        let btn1 = UIButton(frame: CGRect(x: (UIScreen.main.bounds.size.width - 200)*0.5, y: 160, width: 200, height: 50));
        btn1.setTitle("调用OC返回值方法", for: .normal)
        btn1.addTarget(self, action: #selector(funcClick2), for: .touchUpInside)
        self.view.addSubview(btn1)

        let btn2 = UIButton(frame: CGRect(x: (UIScreen.main.bounds.size.width - 200)*0.5, y: 230, width: 200, height: 50));
        btn2.setTitle("调用OC+方法", for: .normal)
        btn2.addTarget(self, action: #selector(funcClickStatic1), for: .touchUpInside)
        self.view.addSubview(btn2)

    }
    
    //1.带参数的swift方法
    func swiftFunc1(par1: String, par2: String) {
        print(par1 + par2)
    }
    
    //2.带返回值的swfit方法
    func swiftFunc2(par: String) -> String {
        return par;
    }
    
    //3.swift静态方法
    static func swiftFuncStatic(par: String) {
        print(par)
    }

    
    //MARK: - 在Swift中调用OC方法
    func funcClick1() {
        let vc = ViewController()
        vc.ocMethod1Par1("Swift调用", par2: "OC多参方法")
    }
    
    func funcClick2() {
        let vc = ViewController()
        print(vc.ocMethod2Par("Swift调用OC含有返回值的方法"))
    }
    
    func funcClickStatic1() {
        ViewController.ocStaticMethodPar("Swift调用OC+方法")
    }
    
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
}

到这里,我们实现了OC 和 Swift的混编。

你可能感兴趣的:(Swift - 17.Objective-C与Swift混编)