在 Swift 中使用 Objective-C 类
如果您要在 App Target 中导入代码(在一个项目中混合 Swift 和 Objective-C),您应该使用 bridging header 文件将 Objective-C 代码公开给 Swift 代码。 [Mixing Swift and Objective-C code in a project]
在这篇文章中,我将介绍如何将 Objective-C 框架导入 Swift 代码
Swift 消费者 -> Objective-C 动态框架
Xcode 版本 10.2.1
创建 Objective-C 框架
创建框架项目或创建框架目标
File -> New -> Project... -> Cocoa Touch Framework
//or
Project editor -> Add a Target -> Cocoa Touch Framework
将生成两个文件:
-
Info.plist - Build Settings -> Info.plist File
-
<product_name>.h - Build Phases -> Headers。这是一个伞头文件,将为消费者[About]打开
将所有.h 文件添加到此伞形文件(.h)
#import "header_1.h"
#import "header_2.h"
添加实现文件.m
Select `.m` file -> Select File Inspectors Tab -> Target Membership -> Select the target
//or
Project editor -> select a target -> Build Phases -> Compile Sources -> add files
在公共区域添加<product_name>.h 中列出的头文件.h (header_1.h, header_2.h)[can not do it] [public target membership]
Select `.h` file -> Select File Inspectors Tab -> Target Membership -> Select the target and make it **public**
//or
Project editor -> select a target -> Build Phases -> Headers -> add files to the **public** zone
构建框架 - ⌘ 命令 + B 或Product -> Build
注意:确保为与客户端代码相同的流程架构构建框架。
查找生成的输出[Build location]
Products group -> <product_name>.framework -> Show in Finder
框架包括
Info.plist
-
Modules 文件夹:
-
module.modulemap[About] [Custom modulemap] 这个文件是自动生成的,因为Build Settings -> Defines Module -> YES
-
Headers 文件夹:
- 来自
Headers 部分的文件。有公共接口/定义
使用 Objective-C 框架的 Swift 消费者
Drag and drop二进制进入Xcode项目[About]
Embed binaries[Library not loaded][Link vs Embed]
Project editor -> select a target -> General -> Embedded Binaries -> path to `<product_name>.framework` file
我会自动将框架添加到:
Project editor -> select a target -> General -> Linked Frameworks and Libraries
Project editor -> select a target -> Build Phases -> Embed Frameworks
Project editor -> select a target -> Build Phases -> Link Binary With Libraries
添加Framework Search paths(FRAMEWORK_SEARCH_PATHS)[Module not found][Recursive path]
Project editor -> select a target -> Build Settings -> Search Paths -> Framework Search paths -> add path to the parent of `<product_name>.framework` file
将模块导入Swift客户端代码[module_name]
import module_name
More examples here