oc專案中使用swift

2020-10-09 18:01:00

一、為什麼寫這篇文章

    我們整個移動開發團隊都在從老的語言向新的語言過度,Android團隊所有專案都在使用Kotlin開發了,但是iOS團隊還在使用OC開發專案。團隊負責人也已經發話了,iOS端從下個新專案開始都要使用swift開發了,對於基本沒怎麼使用過swift的同學來說,馬上用新語言開發專案還是有一定難度、有一定風險的。從OC和swift混編開始,從OC向swift逐漸熟悉過度,是最佳選擇,積累的經驗,降低了難度,也降低了風險!

二、Swift目前現狀

    蘋果在WWDC2014正式釋出Swift,目的是用於替代OC語言。在之後的時間裡經歷了標準庫變動,語法的增減,特性變動,幾乎每一年 Swift 都會迎來比較大的改動,甚至 API 都發生了變化,讓很多第一批吃螃蟹的開發者苦不堪言,戲稱《Swift 從入門到重學》。如今已是2020年了,經過 6 年多的不斷迭代更新,WWDC2019蘋果釋出了Swift5.0,蘋果終於宣佈了Swift的穩定。這標誌著Swift這門語言已經趨於穩定,語法已經不會再大變,已經有越來越多的個人和公司在使用Swift,現在也到了重拾Swift的時候了。

三、本篇文章主要內容

1、在OC工程中設定swift需要的基本環境

2、oc和swift頁面相互跳轉,oc和swift屬性相互呼叫,oc和swift方法相互呼叫,oc和swift頁面delegate相互傳值,oc和swift頁面block相互傳值

1、環境的基本設定

1.1、新建一個基於OC的工程名為OcAndSwift,已經存在的OC工程也是一樣的。

1.2、工程設定設定

新建一個OC類OCClass1ViewController

新建一個swift類SwiftClass1ViewController.swift

完整目錄結構

2、實現 頁面相互跳轉返回,屬性相互呼叫,方法相互呼叫,delegate傳值,block傳值

2.1、程式碼實現

ViewController.m

//
//  ViewController.m
//  OcAndSwift
//
//  Created by AiRongTang on 2020/9/29.
//  Copyright © 2020 AiRongTang. All rights reserved.
//
/**
 主介面
 */
#import "ViewController.h"
#import "OcAndSwift-Swift.h"

@interface ViewController ()<SwiftClass1ViewControllerDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"主頁";
    [self createButton];
}

/// 建立按鈕
-(void)createButton{
    //跳轉按鈕
    UIButton *butotn = [UIButton buttonWithType:UIButtonTypeSystem];
    [butotn addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    butotn.frame = CGRectMake(0, 64, 150, 40);
    [butotn setTitle:@"跳轉到swift1" forState:UIControlStateNormal];
    [butotn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    butotn.tag = 1;
    [self.view addSubview:butotn];
    
    //呼叫swift方法的按鈕
    UIButton *ocCallButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [ocCallButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    ocCallButton.frame = CGRectMake(0, 64+40+10, 150, 40);
    [ocCallButton setTitle:@"呼叫swift的方法" forState:UIControlStateNormal];
    [ocCallButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    ocCallButton.tag = 2;
    [self.view addSubview:ocCallButton];
}

/// 按鈕點選事件
/// @param sender 點選的按鈕
-(void)buttonAction:(UIButton*)sender{
    SwiftClass1ViewController *class1 = [[SwiftClass1ViewController alloc]init];
    switch (sender.tag) {
        case 1:{
            //跳轉到Swift介面
            class1.delegate = self;
            [self.navigationController pushViewController:class1 animated:YES];
            //實現swift類物件的block方法
            class1.myBlock = ^(NSString * _Nonnull data) {
                NSLog(@"myEidtorBlock==%@",data);
            };
            break;
        }
        case 2:{
            //呼叫swift的方法
            NSString *string = [class1 ocCallMethod:@"ocCallMethod成功"];
            NSLog(@"ocCallMethodReturn==%@",string);
            break;
        }
        default:
            break;
    }
    
}

/// 實現swift類物件的代理方法
/// @param data 接受資料
-(void)delegateMethod1:(NSString *)data{
    NSLog(@"delegateMethod1==%@",data);
}

@end

SwiftClass1ViewController.swift

//
//  SwiftClass1ViewController.swift
//  OcAndSwift
//
//  Created by AiRongTang on 2020/9/29.
//  Copyright © 2020 AiRongTang. All rights reserved.
//
/**
 Swift介面
 */
import UIKit

//必須加上@objc 代理才能在oc類中可見。
@objc(SwiftClass1ViewControllerDelegate)
protocol SwiftClass1ViewControllerDelegate:NSObjectProtocol {
    func delegateMethod1(_ data: String);
}
//必須加上@objcMembers SwiftClass1ViewController中的屬性才能在oc類中可見。
@objcMembers
class SwiftClass1ViewController: UIViewController, OCClass1ViewControllerDelegate {
    //定義delegate
    var delegate:SwiftClass1ViewControllerDelegate?
    
    //定義Block
    typealias SwiftClass1ViewControllerBlock = (_ tttt:String) -> Void
    var myBlock:SwiftClass1ViewControllerBlock?;
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.title = "swift介面1";
        self.createButton()
    }
    
    /// 建立按鈕
    func createButton(){
        //跳轉按鈕
        let btn = UIButton(frame: CGRect(x: 0, y: 100, width:150, height: 40))
        btn.setTitle("跳轉到OC介面1", for: .normal);
        btn.setTitleColor(UIColor.red, for: .normal);
        btn.tag = 1;
        view.addSubview(btn);
        btn.addTarget(self, action: #selector(btnClicked), for: .touchUpInside);
        
        //呼叫OC方法的按鈕
        let swiftCallButton = UIButton(frame: CGRect(x: 0, y: 100+40+10, width:150, height: 40))
        swiftCallButton.setTitle("呼叫OC的方法", for: .normal);
        swiftCallButton.setTitleColor(UIColor.red, for: .normal);
        swiftCallButton.tag = 2;
        view.addSubview(swiftCallButton);
        swiftCallButton.addTarget(self, action: #selector(btnClicked(button:)), for: .touchUpInside);
        
        //帶資料返回按鈕
        let returnButton = UIButton(frame: CGRect(x: 0, y: 100+40+40+10, width:150, height: 40))
        returnButton.setTitle("帶資料返回", for: .normal);
        returnButton.setTitleColor(UIColor.red, for: .normal);
        returnButton.tag = 3;
        view.addSubview(returnButton);
        returnButton.addTarget(self, action: #selector(btnClicked(button:)), for: .touchUpInside);
    }
    
    /// 按鈕點選事件
    /// - Parameter button: 點選的按鈕
    @objc func btnClicked(button:UIButton){
        let vc = OCClass1ViewController();
        switch button.tag {
        case 1  :
            //跳轉到OC介面
            vc.delegate = self;
            vc.selectConfirmBlock = {(data:String?)in
                print("selectConfirmBlock==",data!);
            }
            self.navigationController?.pushViewController(vc, animated: true);
        case 2  :
            //呼叫OC的方法
            let string = vc.swiftCallMethod("swiftCallMethod成功");
            print("delegateMethod1==", string);
        case 3  :
            //呼叫delegate返回資料
            if delegate != nil {
                delegate?.delegateMethod1("我是從swift頁面返回的delegate資料");
            }
            //呼叫block返回資料
            if (self.myBlock != nil){
                self.myBlock!("我是從swift頁面返回的block資料");
            }
            self.navigationController?.popViewController(animated: true);
        default :
            print("預設case")
        }
    }
    
    /// 代理方法實現
    /// - Parameter data: 接受資料
    func delegateMethod1(_ data: String) {
        print("delegateMethod1==", data);
    }
    
    /// 供OC呼叫的方法
    /// - Parameter data: OC傳過來的值
    /// - Returns: 返回值
    @objc func ocCallMethod(_ data: String) -> String {
        return data;
    }
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destination.
     // Pass the selected object to the new view controller.
     }
     */
    
}

OCClass1ViewController.h

//
//  OCClass1ViewController.h
//  OcAndSwift
//
//  Created by AiRongTang on 2020/9/29.
//  Copyright © 2020 AiRongTang. All rights reserved.
//
/**
 OC介面
 */
#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

///Delegate
@protocol OCClass1ViewControllerDelegate <NSObject>

-(void)delegateMethod1:(NSString *)data;

@end

///Block回撥
typedef void(^SelectConfirmBlock)(NSString *data);

@interface OCClass1ViewController : UIViewController

@property (nonatomic, copy) SelectConfirmBlock selectConfirmBlock;

@property (nonatomic, weak) id<OCClass1ViewControllerDelegate> delegate;


/// 供swift呼叫的方法
/// @param data swift傳過來的值
-(NSString *)swiftCallMethod:(NSString*)data;


@end

NS_ASSUME_NONNULL_END

OCClass1ViewController.m

//
//  OCClass1ViewController.m
//  OcAndSwift
//
//  Created by AiRongTang on 2020/9/29.
//  Copyright © 2020 AiRongTang. All rights reserved.
//
/**
 OC介面
 */
#import "OCClass1ViewController.h"

@interface OCClass1ViewController ()

@end

@implementation OCClass1ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"OC介面1";
    [self createButton];
    
}

/// 建立按鈕
-(void)createButton{
    UIButton *butotn = [UIButton buttonWithType:UIButtonTypeSystem];
    [butotn addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    butotn.frame = CGRectMake(0, 64, 150, 40);
    [butotn setTitle:@"帶資料返回" forState:UIControlStateNormal];
    [butotn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [self.view addSubview:butotn];
}

/// 按鈕點選事件
/// @param sender 點選的按鈕
-(void)buttonAction:(UIButton*)sender{
    if (self.delegate && [self.delegate respondsToSelector:@selector(delegateMethod1:)]) {
        [self.delegate delegateMethod1:@"我是從OC頁面返回的delegate資料"];
    }
    if (self.selectConfirmBlock) {
        self.selectConfirmBlock(@"我是從OC頁面返回的block資料");
    }
    [self.navigationController popViewControllerAnimated:YES];
}

/// 供swift呼叫的方法
/// @param data swift傳過來的值
-(NSString *)swiftCallMethod:(NSString*)data{
    return data;
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

2.2、操作結果列印

2.3、注意要點

//必須加上@objc 代理才能在oc類中可見。
@objc(SwiftClass1ViewControllerDelegate)
//必須加上@objcMembers SwiftClass1ViewController中的屬性才能在oc類中可見。
@objcMembers

四、最後

    希望大家能喜歡我分享的oc和swift混編這篇文章,希望它能為大家帶來幫助。重點在於熟悉關鍵點的設定以及swift語法的使用。好的技術有很多,好的文章也有很多,只要我們善於總結,樂於分享,發揚人人為我,我為人人的觀念,我們大家都會越來越好。

CSDN連結:https://blog.csdn.net/u011890139/article/details/108967123

demo連結:https://blog.csdn.net/u011890139/article/details/108967123