CAShapeLayer班级创作

时间:2015-07-22 21:02:03

标签: objective-c swift animation cabasicanimation cashapelayer

我找到了一个用Swift编写的精彩教程,用于在我的应用程序打开时创建动画。它是用Swift编写的,所以我是Objective-C-ifing它正在处理我正在进行的项目,但是我在添加动画时遇到了一些麻烦。 Swift有效,但我无法弄清楚我的Objective-C版本有什么问题。

Creating a Complex Loading Animation in Swift

CAShapeLayer类的Swift版本:

func expand() {
    var expandAnimation: CABasicAnimation = CABasicAnimation(keyPath: "path")
    expandAnimation.fromValue = ovalPathSmall.CGPath
    expandAnimation.toValue = ovalPathLarge.CGPath
    expandAnimation.duration = animationDuration
    expandAnimation.fillMode = kCAFillModeForwards
    expandAnimation.removedOnCompletion = false
    // the following line I'm having trouble converting to Objective-C
    addAnimation(expandAnimation, forKey: nil)
}

Objective-C版本:

- (void)expand {
    CABasicAnimation *expandAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
    expandAnimation.fromValue = (__bridge id)(_ovalPathSmall.CGPath);
    expandAnimation.toValue = (__bridge id)(_ovalPathSquishHorizontal.CGPath);
    expandAnimation.duration = self.animationDuration;
    expandAnimation.fillMode = kCAFillModeForwards;
    expandAnimation.removedOnCompletion = NO;
    // I can't figure out how to "convert" this to Objective-C
    // addAnimation(expandAnimation, forKey: nil)

}

初始化器:

我怀疑我正在使用初始化程序,所以这里是工作Swift的代码和我下面的Objective-C-ified版本。

Swift版本:

let animationDuration: CFTimeInterval = 0.3

override init!() {
    super.init()
    fillColor = Colors.red.CGColor
    path = ovalPathSmall.CGPath
}

required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

Objective-C版本:

这是我在.m文件中模仿初始化程序的尝试:

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.animationDuration = 0.3;
        self.fillColor = [UIColor redColor].CGColor;
        self.path = self.ovalPathSmall.CGPath;
    }
    return self;
}

感谢您阅读,我欢迎您的意见。

1 个答案:

答案 0 :(得分:1)

要回答您的直接问题,我认为您只需要[self addAnimation ...],但我不知道您尝试了什么。

要回答你的评论,至少在这一点上,这很容易。请参阅:https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-XID_78的混合和匹配部分。

简短版本是Swift编译器首先运行,并根据项目名称生成Obj-C存根,Obj-C编译器可以在单个头文件中理解这些存根。此文件在构建输出(派生数据等)中生成。根据上面链接中的示例,您需要将该文件导入到Ojb-C代码中。

#import "ProductModuleName-Swift.h"