我在swift2中使用Objective-C类,我如何实现委托方法并绑定该委托 [英] I am using objective-c classes in swift2 , how i can implement delegate methods and bind that delegate

查看:139
本文介绍了我在swift2中使用Objective-C类,我如何实现委托方法并绑定该委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用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");
    }
}

i am using custom UIView class in my project which is written in obj-c and now i want to bind delegate in swift class and how can i implement that in swift class.

解决方案

When you add objective-c classes in swift project, you'll be prompted for

'Create bridging header' -> click on 'create bridging header'. Now you can use objective-c code in your swift.

  • In your Objective-C bridging header file, import every Objective-C header you want to expose to Swift.
  • In Build Settings, in Swift Compiler - Code Generation, make sure the Objective-C Bridging Header build setting under has a path to the bridging header file. The path should be relative to your project, similar to the way your Info.plist path is specified in Build Settings. In most cases, you should not need to modify this setting.

For more detail refer

Modifying the solution as per your problem:

//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");
    }
}

这篇关于我在swift2中使用Objective-C类,我如何实现委托方法并绑定该委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆