使用 Objective-C 中的 Swift 类和枚举

bha*_*tsb 1 enums class objective-c swift

我已经在我的 Objective-C 项目中包含了一组 swift 类和它们的 swift 依赖项。我已经为其他 swift 库做了这个,所以像 Obj-C Generated Interface Header 这样的东西已经存在。

这是我希望使用的类:

    @objc public class StatusBarNotificationBanner: BaseNotificationBanner 
    {
    override init(style: BannerStyle) {
        super.init(style: style)
        bannerHeight = 20.0

        titleLabel = MarqueeLabel()
        titleLabel?.animationDelay = 2
        titleLabel?.type = .leftRight
        titleLabel!.font = UIFont.systemFont(ofSize: 12.5, weight: UIFontWeightBold)
        titleLabel!.textAlignment = .center
        titleLabel!.textColor = .white
        addSubview(titleLabel!)

        titleLabel!.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.left.equalToSuperview().offset(5)
            make.right.equalToSuperview().offset(-5)
            make.bottom.equalToSuperview()
        }

        updateMarqueeLabelsDurations()
    }

    public convenience init(title: String, style: BannerStyle = .info) {
        self.init(style: style)
        titleLabel!.text = title
    }

    public convenience init(attributedTitle: NSAttributedString, style: BannerStyle = .info) {
        self.init(style: style)
        titleLabel!.attributedText = attributedTitle
    }

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

}
Run Code Online (Sandbox Code Playgroud)

这就是人们在 swift 中使用该类的方式:

let banner = StatusBarNotificationBanner(title: title, style: .success)
banner.show()
Run Code Online (Sandbox Code Playgroud)

我如何在 Obj-C 中实例化 StatusBarNotificationBanner 并调用它的 show() 方法?

另外,如何传递枚举参数样式?

这是枚举:

public enum BannerStyle {
    case danger
    case info
    case none
    case success
    case warning
}
Run Code Online (Sandbox Code Playgroud)

我想枚举需要采用以下形式:

@objc public enum BannerStyle: Int {
    case danger
    case info
    case none
    case success
    case warning
}
Run Code Online (Sandbox Code Playgroud)

但我仍然不知道如何在 Obj-C 中将它作为参数传递,我不明白为什么必须指定 Int?枚举不是隐式 Int 吗?

mat*_*att 5

枚举不是隐式 Int 吗?

并不真地。Objective-C 根本看不到 Swift 枚举。在 Swift 中,枚举是一种对象类型。Objective-C 不知道任何此类对象类型;它唯一的对象是类。(在 Objective-C 中,枚举只是带有名称的数字。)因此,Swift 枚举类型、采用或生成 Swift 枚举的方法、Swift 枚举属性都不会暴露给 Objective-C

但是,在您说的特殊情况下@objc enum BannerStyle: Int,它会为您翻译成一个 Objective-C 枚举。因此,在 Objective-C 中,诸如BannerStyleDanger和 之类的名称BannerStyleInfo将栩栩如生。但它们只是整数。