首页 > 解决方案 > 如何从 Swift 中的 NSTokenAttachmentCell 继承?

问题描述

在 Swift(和 Objective-c)中,你通常不能继承 NSTokenAttachmentCell。但是,如果我创建一个桥接头并为 NSTokenAttachmentCell 定义一个标头,我就可以在 Swift 中对它进行子类化。

这是 objective-c 中的一个示例。NSTokenAttachmentCell 不公开。但是,如果为它创建头文件,则可以对其进行子类化。你不能在 Swift 中创建头文件。除了在桥接头中创建一个之外,还有没有办法在 Swift 中做到这一点?

#import <Cocoa/Cocoa.h>
#import "NSTokenAttachmentCell.h"

@interface BWTokenAttachmentCell : NSTokenAttachmentCell {}
@end

标签: swift

解决方案


我创建了一个 Swift 系统模块swift package init --type executable。除了标准 SPM 文件之外,唯一的文件是不公开的自定义头文件。

我现在可以将系统模块包用作依赖项,并将通常无法子类化的 Apple 类进行子类化。

这是完整的示例。

git clone https://github.com/saltzmanjoelh/TokenExample && cd TokenExample && swift test

你会看到正确的继承

Success: - <TokenExample.CustomTokenAttachmentCell: 0x7fc1be803d10> #0
  - super: NSTokenAttachmentCell
    - super: NSTextAttachmentCell
      - super: NSCell
        - super: NSObject

我使用这两个指南作为参考:

运送-c-code-with-swift-packages

导入-c-library-into-swift


推荐阅读