Object-C 和 Swift 混编 之一 Object-C 中调用 Swift

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
}
做了上面的转变后在OC中就可以使用Swift的Enum类型了

使用方法如下:

       //NVActivityIndicatorType type  = NVActivityIndicatorTypePacman;
       //NVActivityIndicatorType type  = NVActivityIndicatorTypeBallClipRotate;
       //NVActivityIndicatorType type  = NVActivityIndicatorTypeBallScale;

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


源代码下载





  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值