【问题标题】:Using Swift Class and Enum from Objective-C在 Objective-C 中使用 Swift 类和枚举
【发布时间】:2017-04-27 03:10:41
【问题描述】:

我在我的 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)
    }

}

这是在 swift 中使用类的方式:

let banner = StatusBarNotificationBanner(title: title, style: .success)
banner.show()

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

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

这是枚举:

public enum BannerStyle {
    case danger
    case info
    case none
    case success
    case warning
}

我猜枚举需要采取以下形式:

@objc public enum BannerStyle: Int {
    case danger
    case info
    case none
    case success
    case warning
}

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

【问题讨论】:

    标签: objective-c swift class enums


    【解决方案1】:

    枚举不是隐含的 Int 吗?

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

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

    【讨论】:

    • 感谢您回答有关枚举的部分问题,但我更大的问题和问题是如何实例化此类并从 Objective 调用 show 方法(以枚举值作为参数之一) -C.
    • 您可以通过查看自动生成的 Objective-C 桥接头轻松找到这一切。最简单的方法是通过命令单击您的 Objective-C 文件导入它的桥接头的名称。
    • 同样的答案。查看桥接头并查看该类的 Objective-C 初始化程序是什么。
    • 感谢 init 的帮助,但我仍然没有看到基类中的 show 方法。我在基类前面加上了@objc,但在该方法的桥接头中没有看到任何内容。它是公开的。
    • 好吧,你没有展示基类,所以我对它一无所知。我也对show 方法一无所知。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-14
    • 2016-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多