一、Swift调用OC
- 创建一个Swift语言的工程;
-
用OC语言创建一个Person类:
Swift调OC-1
此时会出现一个对话框,点击 “Create Bridging Header”
Swift调OC-2 -
此时会出现一个“Swift调OC-Bridging-Header.h”文件,在这个文件里面导入OC类的头文件:
在Swift调OC-Bridging-Header文件中导入OC的头文件 - 这是就可以在Swift中调用OC了:
- Person的头文件
//
// Person.h
// Swift调OC
//
// Created by YJW on 17/4/5.
// Copyright © 2017年 yijiang. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Person : NSObject
/** name */
@property(nonatomic,strong) NSString *name;
/** age */
@property(nonatomic,assign) int age;
-(void)createPerson:(NSString *)name age:(int)age;
@end
- Swift中调用
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let p = Person()
p.createPerson("yijiang", age: 25)
p.name = "yijiangwang"
p.age = 18
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
二、OC中调Swift
- 创建一个OC工程;
-
创建一个Swift类,此时出现对话框:
创建一个Swift类
选择“Don't Create”;
- 在Swift文件中定义属性和方法:默认状态下,类和属性以及方法都是internal权限,此时要设置它们的权限为public,才能被外界访问。
//
// Student.swift
// OC调Swift
//
// Created by YJW on 17/4/5.
// Copyright © 2017年 yijiang. All rights reserved.
//
import UIKit
public class Student: NSObject {
public var name = "yijiang"
public func testStudent(age:Int,score:Int) -> String {
return "12345"
}
}
//定义一个协议
@objc
public protocol StudentProtocol {
func testProtocol()
}
如果要求Swift中的协议能被OC调用时,需要将协议的权限改为public,并且要使用@objc修饰。
- 在OC中导入“项目名-Swift.h”
#import "OC调Swift-Swift.h"
此时Xcode会进行一系列配置,如下图可以查找到:
项目名-Swift.h
- 在OC中调用Swift:
//
// ViewController.m
// OC调Swift
//
// Created by YJW on 17/4/5.
// Copyright © 2017年 yijiang. All rights reserved.
//
#import "ViewController.h"
#import "OC调Swift-Swift.h"
@interface ViewController ()
/** 协议 */
@property(nonatomic,weak)id<StudentProtocol> delegate;
@end
@implementation ViewController
-(void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
Student *stu = [[Student alloc] init];
stu.name = @"yijiang";
[stu testStudentWithAge:24 score:98];
}
-(void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
网友评论