在 Objective-C 中使用 Swift 协议

Using a Swift protocol in Objective-C(在 Objective-C 中使用 Swift 协议)
本文介绍了在 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 协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why local notification is not firing for UNCalendarNotificationTrigger(为什么没有为UNCalendarNotificationTrigger触发本地通知)
Pushing UIViewController above UITabBar(将UIView控制器推送到UITabBar上方)
Dropbox Files.download does not start when number of files in folder is gt; 1000(当文件夹中的文件数为1000时,Dropbox Files.Download不会启动)
appearance().setBackgroundImage Not Working On Custom Class(外观().setBackoundImage在自定义类上不起作用)
How to stop UIBarButtonItem text from truncating?(如何阻止UIBarButtonItem文本被截断?)
Show/Hide barButtonItem(显示/隐藏barButtonItem)