在Objective-C中使用Swift协议

在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的文档页面涵盖了这个问题。