在 Objective-C 中使用 Swift 协议

2023-07-28移动开发问题
8

本文介绍了在 Objective-C 中使用 Swift 协议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在将我的项目从 Objective-c 转换为 Swift,我正在使用一个 Swift 类,我有一个 protocol 我正在尝试在一个 Objective-c 类中访问.我的问题是,在objective-c 类中无法访问delegate.这是我的快速课程:

I'm working on converting my project from Objective-c to Swift, and a Swift class I'm using, I have a protocol I'm trying to access in an Objective-c class. My problem is, the delegate is not accessible in the objective-c class. Here is my swift class:

protocol RateButtonDelegate {
    func rateButtonPressed(rating: Int)
}

class RateButtonView: UIView {


    var delegate: RateButtonDelegate?

    var divider1: UIView!
    var divider2: UIView!
}

当我查看 MyProject-Swift.h 文件时,我没有看到 delegate:

When I look at the MyProject-Swift.h file, I don't see the delegate:

@interface RateButtonViewTest : UIView
@property (nonatomic) UIView * divider1;
@property (nonatomic) UIView * divider2;
@end

当我尝试在我的 Objective-c 类中使用 rateButtonView.delegate 时,出现编译器错误.

and when I try to use rateButtonView.delegate in my Objective-c class, I get a compiler error.

有人知道这个问题吗?如何在 Objective-c 中访问 Swift 协议?

Anyone know the issue? How do access a Swift protocol in Objective-c?

推荐答案

您需要使用 @objc 属性标记您的协议,以便它可以从 Objective-C 访问:

You need to mark your protocol with the @objc attribute for it to be accessible from Objective-C:

@objc protocol RateButtonDelegate {
    func rateButtonPressed(rating: Int)
}

Apple 文档中的此页面 涵盖了该问题.

这篇关于在 Objective-C 中使用 Swift 协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

硬件音量按钮更改应用程序音量
Hardware Volume buttons change in app volume(硬件音量按钮更改应用程序音量)...
2024-08-12 移动开发问题
10

Cocos2d - 如何检查不同层中对象之间的交集
Cocos2d - How to check for Intersection between objects in different layers(Cocos2d - 如何检查不同层中对象之间的交集)...
2024-08-12 移动开发问题
8

突出显示朗读文本(在 iPhone 的故事书类型应用程序中)
Highlight Read-Along Text (in a storybook type app for iPhone)(突出显示朗读文本(在 iPhone 的故事书类型应用程序中))...
2024-08-12 移动开发问题
9

如何将 32 位 PNG 转换为 RGB565?
How to convert 32 bit PNG to RGB565?(如何将 32 位 PNG 转换为 RGB565?)...
2024-08-12 移动开发问题
21

正确的 cocos2d 场景重启?
Proper cocos2d scene restart?(正确的 cocos2d 场景重启?)...
2024-08-12 移动开发问题
7

游戏中心 facebook 喜欢
Game center facebook like(游戏中心 facebook 喜欢)...
2024-08-12 移动开发问题
3