在Objective-C中使用Swift协议 [英] Using a Swift protocol in Objective-C

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

问题描述

我正在努力将我的项目从Objective-c转换为Swift,并且正在使用Swift类,我有一个协议我正在尝试访问在Objective-C类中。我的问题是,在Objective-C类中不能访问委托。这是我的快速课:

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 文件,我没有看到委托

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

当我尝试使用 rateButtonView.delegate 在我的Objective-c类中,我收到编译器错误。

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协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆