如何在Objective-C文件中访问swift类

问题描述 投票:3回答:2

我有一个快速的项目,并且在该项目中导入了一个单例的,由目标C编码的类。

我尝试导入productname_swift.h文件,但是没有运气。

我如何访问该单例课程中的swift类别?

ios objective-c iphone swift swift2
2个回答
4
投票

Swift中的项目:要在Objective C中使用Swift类

要使用Objective C中的Swift类],请按照给定的步骤进行:

  1. 创建一个名为User的Objective C类。
  2. 带有“您想配置一个Objective-C桥接标题的弹出窗口”。选择创建桥接标题
  3. enter image description here

User.h

#import <Foundation/Foundation.h>

@interface User : NSObject

+(id) sharedUser ;

@end

User.m

#import "User.h"
#import "SwiftInObjectiveC-swift.h"


@implementation User


//Singleton of User

+(id)sharedUser{

    static User *sharedUser = nil;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        sharedUser = [[self alloc] init];

        //Class Method of ViewController.swift
        [ViewController mySwiftClassFunction];


        //Instance Method of ViewController.swift
        ViewController *vc = [[ViewController alloc] init];
        [vc mySwiftFunction];

    });
    return sharedUser;
}

-(void) myObjcectivecMethod {

    ViewController *vc = [[ViewController alloc] init];
    [vc mySwiftFunction];

}
  1. 在.swift类的类名前面添加@objc。>>

     import UIKit
    
     @objc class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func mySwiftFunction() {
    
        print("Swift Function")
    }
    
    class func mySwiftClassFunction (){
    
        print("Swift Class Function")
    
    }
    
    }
    
  2. 转到构建设置。

  • 设置产品模块名称

    :项目名称
  • enter image description here

    1. 设置定义模块
    :是

    enter image description here

    1. 设置嵌入的内容包含Swift
    :是

    enter image description here

    1. 设置安装Objective-C兼容性标题
    :是

    enter image description here

    1. 设置Objective-C桥接标题
    :SwiftInObjectiveC / SwiftInObjectiveC-Bridging-Header.h

    enter image description here

    1. *。m
    文件中的[[导入自动生成的标题“ ProjectName-swift.h”。清理并运行您的项目。
  • 它将起作用!!
  • 单击Mix and Match的Apple链接以获取详细信息。
  • enter image description here

    在Objective-C中使用Swift类非常简单。只需按照下面给出的步骤

      打开您的Objective-C项目。
  • 向项目添加新的swift文件。
  • 将打开一个默认对话框以创建一个桥接标题(如果是,默认情况下不会打开,请添加桥接头文件。
  • 转到构建设置,键入Swift Compiler,您将看到您的Swift编译器中的ProjectName-Swift.h-如下所示enter image description here
  • 导入您想要的快速类构建和运行。

  • 2
    投票

    在Objective-C中使用Swift类非常简单。只需按照下面给出的步骤

    © www.soinside.com 2019 - 2024. All rights reserved.