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…

猜你喜欢

转载自blog.csdn.net/weixin_34150224/article/details/91397819