如何从Objective-C调用Swift初始化方法

时间:2019-04-09 04:34:34

标签: objective-c swift xcode10.2

我正在使用Xcode 10.1,并在Objective-C项目中使用了SWIFT_VERSION 3.0。 以下代码在Swift 3上运行良好。

RichTextEditor.swift:

init(frame: CGRect, editAccess: Int) {
    super.init(frame:frame)
}

Objective-C类调用上述方法:

self.rchTextControl = [[RichTextEditor alloc] initWithFrame:CGRectMake(2, cellRowHeight, tableView.tableView.bounds.size.width-4, cellMessageHeight-cellRowHeight) editAccess:[sectionCtrlEditAccessValue intValue]];

以上Objective-C代码可在Swift 3上使用,一旦将其更改为SWIFT_VERSION 4,就会发生以下错误。

enter image description here

如何解决此问题?我正在谷歌上搜索,但找不到解决方案。

1 个答案:

答案 0 :(得分:1)

您需要在方法声明中添加@objc才能在目标c中访问它。 像这样

class RichTextEditor : UIView {

override init(frame: CGRect) {
    super.init(frame: frame)
}
@objc init(frame: CGRect, editAccess: Int) {
    super.init(frame:frame)
}
required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}
}