简体   繁体   English

在目标C类中使用委托调用swift方法

[英]Use delegate in objective c class to call swift method

I have two files 我有两个档案

Question.m
Question.h

These two are written by Objective-C 这两个是由Objective-C编写的

MainView.swift

This is written by Swift 这是斯威夫特写的

Question Class has the delegate 问题班有代表

@interface Question : NSObject{

    id delegate;// put MainViewController here

    - (void)trythisfunction{
         [delegate test] // compiler doesn't find this method.
    } 
}

and I make class instance and put MainViewController as delegate of Question in MainViewController.swift 然后创建类实例,并将MainViewController作为MainViewController.swift中Question的委托

 class MainViewController: UIViewController {
        override func viewDidLoad(){
            q = Question()
            q.delegate = self // put self in delegate
         }
         func test(){
             NSLog("test is OK") 
         } 
 }

However Compiler found error [delegate test] Question.m:169:19: No known instance method for selector 'test:' 但是,编译器发现错误[委托测试] Question.m:169:19:选择器'test:'没有已知的实例方法

How can I solve this?? 我该如何解决?

You need to make few changes. 您需要进行一些更改。

Below class declaration doesn't compile because you can't declare variables inside interface . 下面的类声明无法编译,因为您无法在interface声明变量。

    @interface Question : NSObject{

    id delegate;

    - (void)trythisfunction {
         [delegate test] 
    } 
    }

I have fixed above and the class now looks like this, 我已经在上面固定,现在班级看起来像这样,

 # Question.h file
 #import <Foundation/Foundation.h>

 @interface Question : NSObject
 @property (nonatomic, strong) id delegate;
 @end

Below is the implementation of the class 下面是该类的实现

 # Question.m file
 #import "Question.h"

 @implementation Question

 @synthesize delegate;

 - (void)trythisfunction{
     [delegate test];
 }
 @end

As we are integrating this swift and so we will need a Bridging Header whose content look like. 当我们集成这种快速方法时,我们将需要一个内容类似于的桥接头

  #import "Test.h"

Finally in your swift class now you can import this class 最后,在您的快速班级中,您现在可以导入该班级

import UIKit

class MainViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        let q = Test()
        q.delegate = self
    }
    func test(){
        NSLog("test is OK")
    }
}

And above code works like a charm. 上面的代码就像一个魅力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM