簡體   English   中英

我在swift2中使用Objective-C類,我如何實現委托方法並綁定該委托

[英]I am using objective-c classes in swift2 , how i can implement delegate methods and bind that delegate

在此處輸入圖片說明 我在用obj-c編寫的項目中使用自定義UIView類,現在我想在swift類中綁定委托,如何在swift類中實現委托。

在swift項目中添加Objective-C類時,系統會提示您輸入

“創建橋接頭” ->單擊“創建橋接頭”。 現在,您可以快速使用Objective-C代碼。

  • 在您的Objective-C橋接頭文件中,導入要公開給Swift的每個Objective-C頭。
  • 在“構建設置”的“ Swift編譯器-代碼生成”中,確保下面的“ Objective-C橋接頭”構建設置具有橋接頭文件的路徑。 該路徑應相對於您的項目,類似於在“構建設置”中指定Info.plist路徑的方式。 在大多數情況下,您無需修改​​此設置。

有關更多詳細信息, 請參閱

根據您的問題修改解決方案:

//Objective-c class
// Test.h
#import <Foundation/Foundation.h>

@protocol TestDelegate <NSObject>

- (void)testMethod;

@end

@interface Test : NSObject

@property (weak, nonatomic) id<TestDelegate> delegate;
@end

//Test.m
#import "Test.h"

@implementation Test
@synthesize delegate;

- (void)callDelegate
{
    [delegate testMethod];
}

@end

//Swift bridging header

//
//  Use this file to import your target's public headers that you would like to expose to Swift.
//

#import "Test.h"

//Swift class

class ViewController: UIViewController, TestDelegate {
.
.
.
    func testMethod() {
        print("Delegate");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM