版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/huangshanfeng/article/details/52267518
oc与swift混编
一、建立oc工程
二、OC调用Swift写的类
新建Swift类(Demo.swift)
代码块
//
// Demo.swift
// Test
//
// Created by 1391 on 16/8/21.
// Copyright © 2016年 cuilu. All rights reserved.
//
import UIKit
class Demo: NSObject {
func goToTest()->String {
return "start swift"
}
}
引用头文件
因OC调用swift 的头文件是系统自动生成的。(注意,系统设置的头文件,在工程中是看不到的。)
那如何找到这个头文件呢?
步骤:
选中targets->build settings
Product Module Name + Swift.h即为头文件
栗子:OcAndSwift-Swift.h
导入头文件
ViewController.m文件
#import "ViewController.h"
#import "OcAndSwift-Swift.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
TestSwift *testSwift = [[TestSwift alloc] init];
NSString *str = [testSwift goToTest];
NSLog(@"%@",str);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
运行结果如下:
三、Swift调用OC写的类
ViewController.h文件
//
// ViewController.h
// Test
//
// Created by 1391 on 16/8/21.
// Copyright © 2016年 cuilu. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
+ (NSString *)gotoOc;
@end
ViewController.m文件
//
// ViewController.m
// Test
//
// Created by 1391 on 16/8/21.
// Copyright © 2016年 cuilu. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
+ (NSString *)gotoOc{
return @"goto coding";
}
@end
新建swift类(TestViewController.swift)
AppDelegate.m文件(使TestViewController.swift为根控制器)
//
// AppDelegate.m
// Test
//
// Created by 1391 on 16/8/21.
// Copyright © 2016年 cuilu. All rights reserved.
//
#import "AppDelegate.h"
#import "Test-Swift.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
UIWindow *window = [[UIWindow alloc] initWithFrame: [UIScreen mainScreen].bounds];
window.backgroundColor = [UIColor whiteColor];
[window makeKeyAndVisible];
window.rootViewController = [[TestVeiwController alloc] init];
return YES;
}
@end
引入OC头文件到Swfit(重要)
此后在swift中用oc了,用法请继续看
TestViewController.swift文件
//
// TestVeiwController.swift
// Test
//
// Created by 1391 on 16/8/21.
// Copyright © 2016年 cuilu. All rights reserved.
//
import UIKit
class TestVeiwController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
print(ViewController.gotoOc())
}
}