我发现了一个用 Swift 编写的精彩教程,用于在我的应用程序打开时创建动画。它是用 Swift 编写的,所以我正在为我正在从事的项目对其进行 Objective-C 化,但我在添加动画时遇到了一些麻烦。 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 化版本的代码。
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;
}
感谢您的阅读,欢迎您提出意见。
最佳答案
为了回答您的直接问题,我认为您只需要[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 stub 。该文件是在构建输出(派生数据等)中生成的。您需要根据上面链接中的示例将该文件导入到您的 Ojb-C 代码中。
#import "ProductModuleName-Swift.h"
关于objective-c - CAShapeLayer 类创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31573915/