小工具知识网

当前位置: 首页 > 行业知识 > OC与Swift的相互调用

行业知识

OC与Swift的相互调用

2026-11-08 08:34:26 来源:互联网转载

OC调用Swift方法

1、在 Build Settings 搜索 Packaging ,设置 Defines Module 为 YES

 2、新建 LottieBridge.swift 文件,自动生成桥 ProductName-Bridging-Header.h

 3、在 LottieBridge.swift 中,定义Swift类继承于OC类,声明 @objcMembers 或 @objc ,实现相关方法

import UIKitimport Lottie// 所有方法/属性声明@objcMembers class MyLottieView: UIView {    private let animationView = LottieAnimationView()    override init(frame: CGRect) {        super.init(frame: frame)        self.addSubview(animationView)    }    override func layoutSubviews() {        super.layoutSubviews()        animationView.frame = self.bounds    }    public func setLottieFromURL(_ url: URL?) {        if let url = url {            LottieAnimation.loadedFrom(url: url) { [weak self] (animation) in                self?.animationView.animation = animation                self?.play()            }        }    }    public func play() {        animationView.play()    }}// 单个方法/属性声明@objc class MyLottieView: UIView {    private let animationView = LottieAnimationView()    override init(frame: CGRect) {...}    override func layoutSubviews() {...}    @objc public func setLottieFromURL(_ url: URL?) {...}    @objc public func play() {...}}

4、在OC代码中引用 ProductName-Swift.h ,调用Swift相关方法

#import "ProductName-Swift.h"- (void)swiftTest {    MyLottieView *lottieView = [[MyLottieView alloc] initWithFrame:CGRectMake(100, 100, 320, 320)];    [self.view addSubview:lottieView];        NSURL *url = [NSURL URLWithString:@"https://assets9.lottiefiles.com/packages/lf20_N0y2Nj.json"];    [lottieView setLottieFromURL:url];}

Swift调用OC方法

1、在 ProductName-Bridging-Header.h 中加入OC的头声明

#import #import 

2、在Swift代码中调用OC的相关方法

private func OCTest() {    let configuration = URLSessionConfiguration.default    _ = AFURLSessionManager(sessionConfiguration: configuration)}

上一篇:网站二级域名怎么弄?

下一篇:服务器怎么防止被扫描?