1. 程式人生 > IOS開發 >OC和Swift混編(一)——OC與Swift相互呼叫

OC和Swift混編(一)——OC與Swift相互呼叫

WWDC推出了SwiftUI、Combine,僅Swift可用~為了能順利的也吃上SwiftUI,我也打算將自己的專案先從OC慢慢遷移到Swift,所以~一起從混編開始!

建立Swift的view

正常建立檔案,語言選swift

建立Bridging Header

上一步,點完next,系統會提示如下彈框。點create Bridging Header

oc使用Swift檔案

  1. 匯入標頭檔案,在要使用swift的檔案的地方都匯入此標頭檔案,或者將此標頭檔案放入pch裡面,即可使用swift的檔案
#import "OCAndSwift-Swift.h" //專案名稱-Swift.h
複製程式碼

點選進去,可以看到我剛剛建的檔案的,如下所示,有初始化的方法,和我暴露在外面的方法~所有swift檔案都會在這個檔案裡面被“轉化”成OC

2) oc裡面呼叫swift,像呼叫oc一樣,完全看不出來。

    ZTSwiftView *view = [[ZTSwiftView alloc]init];
    [self.view addSubview:view];
    
    __weak typeof(view) weakView = view;
    //點了確認後執行此block
    view.selectColorBlockSwift = ^(NSString * _Nonnull str) {
        __strong typeof(weakView) strongView = weakView;
        //將string賦值給view的button
        [strongView reloadBtnTitleWithTitle:str];
    };
複製程式碼

其中reloadBtnTitleWithTitle方法是swift裡面的方法,swift方法想被oc呼叫,前面需帶objc,如下

    @objc public func reloadBtnTitle(title:NSString){
        confirmButton.backgroundColor = .white
        confirmButton.setTitle(title as String,for: .normal)
    }
複製程式碼

Swift裡面使用oc的view

  1. 將oc的view放入之前系統建立的bridgeHeader裡面

2) swift裡面使用如下,像是swiftView一樣,正常使用

        let ocView = ZTOCView()
        ocView.frame = CGRect(x: 0,y: 0,width: contentView.frame.width,height: contentView.frame.height)
        contentView.addSubview(ocView)
        
        weak var weakSelf = self
        //點ocView中間的view後的block
        ocView.changeColorBlock = {(color : UIColor?) -> Void in
        
            weakSelf?.confirmButton.backgroundColor = color
            weakSelf?.confirmButton.setTitle("確定",for: .normal)
        }
複製程式碼

最後

效果圖如下,是個有些醜的demo~

程式碼 github.com/zttina/OCAn…