OC和Swift混编(一)——OC与Swift相互调用

WWDC推出了SwiftUI、Combine,仅Swift可用~为了能顺利的也吃上SwiftUI,我也打算将本身的项目先从OC慢慢迁移到Swift,因此~一块儿从混编开始!git

建立Swift的view

正常建立文件,语言选swift github

建立Bridging Header

上一步,点完next,系统会提示以下弹框。点create Bridging Headerswift

oc使用Swift文件

  1. 导入头文件,在要使用swift的文件的地方都导入此头文件,或者将此头文件放入pch里面,便可使用swift的文件
#import "OCAndSwift-Swift.h" //项目名称-Swift.h
复制代码

点击进去,能够看到我刚刚建的文件的,以下所示,有初始化的方法,和我暴露在外面的方法~全部swift文件都会在这个文件里面被“转化”成OCbash

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,以下ui

@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~spa

代码 github.com/zttina/OCAn…
相关文章
相关标签/搜索