swift从基础到实践

oc与swift混编

2018-12-04  本文已影响0人  架构师的一小步

互相引用的操作

工程用oc实现引用swift

1.添加swift文件

import Foundation

class SwiftClass: NSObject {
//这里是关键:在oc中调用foo方法需要用@objc定义一下foo函数,否则会报错
    @objc(foo)  
    func foo(){
        print("Hello Swift")
    }
}

2.将prefix Header 改成YES(这里是是否预编译文件的意思)


3.在需要调用swift的oc类中

#import "ObjTest-Swift.h" //#import "{productname}-Swift.h" 项目名称-Swift
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
  //这里调用swift类
    SwiftClass *obj=[SwiftClass new];
  //调用里面的方法
    [obj foo];
    // Do any additional setup after loading the view, typically from a nib.
}

工程用swift实现引用oc

1.添加oc文件

//和正常定义oc文件一样
#import "ObjectClass.h"

@implementation ObjectClass
- (NSString*)foo
{
    return @"tianxiafengshen";
}
@end

2.在SwiftTest-Bridging-Header.h中添加自己创建的oc类, 这个文件是创建oc类默认点击生成的

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

#import "ObjectClass.h"

3.在swift文件中调用oc类

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let label = UILabel(frame: CGRect(x: 0, y: 0, width:self.view.bounds.width, height:240))
        label.textAlignment=NSTextAlignment.center
        
        
        //这里调用了oc的方法
        label.text=ObjectClass().foo()
        //也可以将ObjectClass().foo()拆分
         let obj=ObjectClass()
        label.text=obj .foo()

        self.view.addSubview(label)

        
       
        
        
        // Do any additional setup after loading the view, typically from a nib.
    }


}

工程用oc实现引入swift第三方库

1.pod 方式直接导入或者直接将framework直接拖入
2.Go to your target's settings, hit the "+" under the "Embedded Binaries" section, and select the Charts.framework(在target下的Embedded Binaries下点击+,将framework加入其中)
3.在setting中(Xcode 8.1 and earlier) Under "Build Options", mark "Embedded Content Contains Swift Code"(xcode8.1之前,设置Embedded Content Contains Swift Code为YES)
(Xcode 8.2+) Under "Build Options", mark "Always Embed Swift Standard Libraries"(xcode8.2之后,设置Always Embed Swift Standard Libraries为YES)
4.在要使用的类中:@import Charts;    进行加载

工程用swift引入第三方库直接import这个第三方swift库就可以直接使用

上一篇 下一篇

猜你喜欢

热点阅读