1、创建一个Object-C工程:SwiftInObjectC
2、创建一个Object-C的类:SwiftLan(注意选择)
当创建完成后,Xcode提示下面警告,会提问我们需不需要创意一个Bridge,当然我们选择“Yes”。
这样会在工程中看到一个“SwiftInObjectC-Bridging-Header.h”文件。这个文件的作用可以根据注释看出来:
- //
- // 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 类如下:
- 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类中创建实例子如下:
- SwiftLan *tempString = [[SwiftLan alloc] initWithData:@"Test Swift"];
- NSLog(@"%@",tempString);
7、然后Build & Run 可以在 控制台看见:
运行OK,说明我们已经成功在OC中使用了Swift 方法和类。
8、下面看看二个动效的Swift类,同样的方法:
- [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 的 转换 :
原来的:
- public enum NVActivityIndicatorType {
- case Blank
- case BallPulse
- case BallGridPulse
- case BallClipRotate
- case SquareSpin
- }
添加新的:
- @objc public enum NVActivityIndicatorType :Int{
- case Blank
- case BallPulse
- case BallGridPulse
- case BallClipRotate
- case SquareSpin
- }
使用方法如下:
- //NVActivityIndicatorType type = NVActivityIndicatorTypePacman;
- //NVActivityIndicatorType type = NVActivityIndicatorTypeBallClipRotate;
- //NVActivityIndicatorType type = NVActivityIndicatorTypeBallScale;
注意是NVActivityIndicatorType无缝连接 具体某个枚举的类型Pacman,变为了“NVActivityIndicatorTypePacman”
转自:http://blog.csdn.net/justinjing0612/article/details/47752367