1. 程式人生 > >Swift和Objective-C的相互呼叫

Swift和Objective-C的相互呼叫

(一)Swift呼叫Objective-C

  • 1)已有的OC專案new file 建立swift 檔案
  • 2)出現如下所示的彈框

配置oc橋接標頭檔案的提示
`LearnSwift-Bridging-Header`
  • 3)點選Create Bridging Header
  • 4)自動生成 如下檔案
  • 5)橋接檔案中新增OC的.h檔案(如上圖所示)

  • 6)swift 檔案中呼叫OC 方法 如下圖所示

  • 附程式碼:swift呼叫OC

    override func viewDidLoad() {
        super.viewDidLoad()

        self.title
= "Swift Controller" // Do any additional setup after loading the view. // Utility is Objective-C function,and will be called in swift class // Utility 是 Objective-C 方法,可以在swift類中呼叫Objective-C 方法 let newLabel = UILabel(frame: CGRect(x: 100, y: 100, width: 180, height: 50)) newLabel.text
= Utility.testString() self.view.addSubview(newLabel) self.view.backgroundColor = UIColor.white }

二) OC中呼叫Swift 方法

1) 配置define modules為yes 點選工程檔案->TARGETS->BuildSettings->Packaging 將Defines Modules 設定為yes, Product Module Name設定為你的工程名

setting.png

此時,系統自動生成 “工程名-Swift.h” 這個檔案,只是它不顯示出來你看不見而已,這個檔案不要手動建立。

  • 理解下#import "LearnSwift-Swift.h"
    其實是專案名-Swift.h,這也是Xcode自動生成的,根據你寫的所有swift程式碼,生成一個oc的.h檔案,進行類和方法的宣告,這樣在oc裡引用這個標頭檔案後,就相當於引用了所有swift宣告,可以直接使用了。

2) 在OC 檔案中引入標頭檔案 #import "LearnSwift-Swift.h"其中LearnSwift是專案的名稱,後面的-Swift.h 是固定的寫法 3) 寫OC的程式碼 建立物件

#import "LearnSwift-Swift.h"

- (IBAction)btnClick:(id)sender {

    // SwiftViewController is swift class,and will be called in Objective-C class
    // Utility 是 Objective-C 方法,可以在swift類中呼叫

    SwiftViewController *controller = [[SwiftViewController alloc] init];
    [self.navigationController pushViewController:controller animated:YES];
}

如圖所示

三) 最後

原始碼Demo放在GitHub上面了(點選此處前往)。有興趣的同學可以下載下來看看,順便Star一下哦。

我的微博 @雲峰筆記 簡書 @陳雲峰 多多關注,多提意見,互相學習,互相進步!