您的位置:首页 > 移动开发 > Swift

OC 和 Swift 混编 OC 中调用 Swift

2016-02-18 16:38 309 查看
1、创建一个Object-C工程:SwiftInObjectC



2、创建一个Object-C的类:SwiftLan(注意选择)



当创建完成后,Xcode提示下面警告,会提问我们需不需要创意一个Bridge,当然我们选择“Yes”。



这样会在工程中看到一个“SwiftInObjectC-Bridging-Header.h”文件。这个文件的作用可以根据注释看出来:



[html] view
plain copy

//

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

//

3、下面一步是我们要修改“Bulid Setting” 中的 Defines Module 设置为“Yes” ,同时再看看Product Name 是不是工程的名字。如果是就不用管了

如果不是就改为工程名字。



4、在ViewController中引入头文件 #import "SwiftInObjectC-Swift.h"(SwiftInObjectC是设置的Product
Name)

5、在修改我们创建的SwiftLan 类如下:

[html] view
plain copy

class SwiftLan: NSObject {

/*

// Only override drawRect: if you perform custom drawing.

// An empty implementation adversely affects performance during animation.

override func drawRect(rect: CGRect) {

// Drawing code

}

*/

@objc(initWithData:)

init(data: String){

println(data);

}

}

6、在ViewController类中创建实例子如下:

[html] view
plain copy

SwiftLan *tempString = [[SwiftLan alloc] initWithData:@"Test Swift"];

NSLog(@"%@",tempString);

7、然后Build & Run 可以在 控制台看见:



运行OK,说明我们已经成功在OC中使用了Swift 方法和类。

8、下面看看二个动效的Swift类,同样的方法:

[html] view
plain copy

[self.view addSubview:({

NVActivityIndicatorType type = NVActivityIndicatorTypePacman;

NVActivityIndicatorView *temp = [[NVActivityIndicatorView alloc] initWithFrame:CGRectMake(0,0,80,80) type:type];

temp.center = self.view.center;

[temp startAnimation];

temp;

})];

[self.view addSubview:({

_testLabel = [[LTMorphingLabel alloc]initWithFrame:CGRectMake(0,200,self.view.bounds.size.width,80)];

_testLabel.text = @"";

_testLabel.textAlignment = NSTextAlignmentCenter;

_testLabel.textColor = [UIColor whiteColor];

_testLabel.font = [UIFont systemFontOfSize:28];

_testLabel;

})];

效果如下:



9、说明的一点是Swift的 Enum和 OC的 Enum 的 转换 :

原来的:

[html] view
plain copy

public enum NVActivityIndicatorType {

case Blank

case BallPulse

case BallGridPulse

case BallClipRotate

case SquareSpin

}

添加新的:

[html] view
plain copy

@objc public enum NVActivityIndicatorType :Int{

case Blank

case BallPulse

case BallGridPulse

case BallClipRotate

case SquareSpin

}

做了上面的转变后在OC中就可以使用Swift的Enum类型了

使用方法如下:

[html] view
plain copy

//NVActivityIndicatorType type = NVActivityIndicatorTypePacman;

//NVActivityIndicatorType type = NVActivityIndicatorTypeBallClipRotate;

//NVActivityIndicatorType type = NVActivityIndicatorTypeBallScale;

注意是NVActivityIndicatorType无缝连接 具体某个枚举的类型Pacman,变为了“NVActivityIndicatorTypePacman”

源代码下载

转自:http://blog.csdn.net/justinjing0612/article/details/47752367
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: