美文网首页
Swift and Objective-C in the Sam

Swift and Objective-C in the Sam

作者: 开心迪吧 | 来源:发表于2018-02-05 08:11 被阅读24次

一.在Swift中使用Objective-C 类

步骤1:新建一个Objective-C类,Xcode应该会提示你是否配置一个桥接头,如下:

选择Create Bridging Header,会自动生成一个 `<#YourProjectName#>-Bridging-Header.h `文件。

如果你没有看到这个提示,或者你偶然地删除了这个头文件。

解决办法:你可以添加一个新的 `.h `文件,并把它命名为 <#YourProjectName#>-Bridging-Header.h 。然后在Build Settings 中搜索Objective-C Beidging Header 输入`$(SRCROOT)Folder/<#YourProjectName#>-Bridging-Header.h (推荐)`;或者直接将目录中的`<#YourProjectName#>-Bridging-Header.h`直接拖动到输入框中.(不推荐,因为如果工程路径改变之后会有错误。)

步骤2:在`<#YourProjectName#>-Bridging-Header.h `文件中导入头文件,这里应该不会有代码提示,直接输入即可:`#import “YourCustomOC_Classes.h”`

步骤3:使用这个OC类

 在你的 `* .swift` 文件中,如下:

var instanceOfCustomObject: YourCustomOC_Classes = YourCustomOC_Classes()

instanceOfCustomObject.someProperty = "Hello World"

print(instanceOfCustomObject.someProperty)

instanceOfCustomObject.someMethod()

二 . 在Objective-C项目中使用Swift类

步骤1:新建 *. swfit 文件。Xcode应该会提示你是否配置一个桥接头,选择Create Bridging Header,会自动生成一个 `<#YourProjectName#>-Bridging-Header.h `文件。

步骤2:打开 Build Settings 修改这些参数:

- Defines Module : YES.

- Product Module Name : 你项目名字

- Install Objective-C Compatibility Header : YES

- Objective-C Generated Interface Header : 你项目名字-Swift.h

- Objective-C Bridging Header : ` $(SRCROOT)/myproject-Bridging-Header.h ` 


步骤3 :import Swift interface header in your *.m file

#import "你项目名字-Swift.h"

步骤4:Clean and rebuild your Xcode project.

相关文章

网友评论

      本文标题:Swift and Objective-C in the Sam

      本文链接:https://www.haomeiwen.com/subject/eipszxtx.html