2014年7月15日 星期二

Call Object-C file from Swift

【說明】

此筆記記錄如何用Swift語言去呼叫Object-C檔案內的物件。

此專案在View上面建立一個UILabel,UILabel的文字從自訂的Object-C Class內取得。

【專案開發步驟】

設計使用者介面:

建立一個Single View Application模板的專案,名為CallObjectCFromSwift,並在View上面增加一個UILabel,且建立IBOutlet,如下圖所示。

設計使用者介面
新增Object-C的Class:

點選file -> New -> File...,如下圖所示。

新增檔案
新增一個Object-C File,名稱為Custom,如下圖所示。

新增Object-C File
建立完後會出現訊息詢問是否想要配置一個Object-C header的橋接,如下圖所示,此時點選Yes。

提示訊息
選擇Yes後會建立一個橋接的檔案,如下圖所示。

橋接的檔案
再新增一個檔案,選擇Header File,名稱與.m檔相同Custom,如下圖所示。

新增Header File
修改Custom.h與Custom.m檔案:

Custom.h:

//
//  Custom.h
//  CallObjectCFromSwift
//
//  Created by Hsu,Yi-Sheng on 2014/7/15.
//  Copyright (c) 2014 yisheng. All rights reserved.
//

#import <UIKit/UIKit.h>


@interface Custom : NSObject

@property(nonatomic, strong) NSString *string;

- (void) setCustomString;

@end

Custom.m:

//
//  Custom.m
//  CallObjectCFromSwift
//
//  Created by Hsu,Yi-Sheng on 2014/7/15.
//  Copyright (c) 2014 yisheng. All rights reserved.
//

#import "Custom.h"

@implementation Custom

- (void) setCustomString {
    self.string = @"Hello";
}

@end

在橋接檔案內新增Custom Class的import:

如下圖所示,新增Custom.h的import。

import Custom.h
修改ViewController.swift檔案:

//
//  ViewController.swift
//  CallObjectCFromSwift
//
//  Created by Hsu,Yi-Sheng on 2014/7/15.
//  Copyright (c) 2014 yisheng. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet var label: UILabel
                            
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        var customClass:Custom = Custom()
        customClass.setCustomString()
        
        label.text = customClass.string
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}
ViewDidLoad內建立一個名為customClass的變數,資料型態為Custom。利用customClass取得Custom Class內的function。將label的文字設定為customClass的string。


【執行結果】


沒有留言:

張貼留言