我最近發現了一些UIView動畫代碼,並注意到它沒有正確使用animateKeyframesWithDuration:delay:options:animations:completion:
方法,並且一直試圖修復它,但由於某些原因,動畫並不相同。UIView animateKeyframesWithDuration vs標準動畫塊動畫不同
下面是我找到的代碼:
view.transform = CGAffineTransformMakeTranslation(300, 0);
[UIView animateKeyframesWithDuration:duration/4 delay:delay options:0 animations:^{
// End
view.transform = CGAffineTransformMakeTranslation(-10, 0);
} completion:^(BOOL finished) {
[UIView animateKeyframesWithDuration:duration/4 delay:0 options:0 animations:^{
// End
view.transform = CGAffineTransformMakeTranslation(5, 0);
} completion:^(BOOL finished) {
[UIView animateKeyframesWithDuration:duration/4 delay:0 options:0 animations:^{
// End
view.transform = CGAffineTransformMakeTranslation(-2, 0);
} completion:^(BOOL finished) {
[UIView animateKeyframesWithDuration:duration/4 delay:0 options:0 animations:^{
// End
view.transform = CGAffineTransformMakeTranslation(0, 0);
} completion:^(BOOL finished) {
}];
}];
}];
}];
有兩個問題:
- 每個人都應該真正使用關鍵幀動畫,而不是結束塊內嵌套的動畫。
- 使用
animateKeyframesWithDuration:delay:options:animations:completion:
時,應該調用動畫塊內的addKeyframeWithRelativeStartTime:relativeDuration:animations:
方法。如果你不調用這個方法,那麼這個方法的行爲就像一個標準的UIView動畫塊。
See Apple's documentation regarding this method here.
所以,我想通過正確使用此方法來解決這個問題:
view.transform = CGAffineTransformMakeTranslation(300, 0);
double frameDuration = 1.0/4.0; // 4 = number of keyframes
[UIView animateKeyframesWithDuration:duration delay:delay options:0 animations:^{
[UIView addKeyframeWithRelativeStartTime:0*frameDuration relativeDuration:frameDuration animations:^{
view.transform = CGAffineTransformMakeTranslation(-10, 0);
}];
[UIView addKeyframeWithRelativeStartTime:1*frameDuration relativeDuration:frameDuration animations:^{
view.transform = CGAffineTransformMakeTranslation(5, 0);
}];
[UIView addKeyframeWithRelativeStartTime:2*frameDuration relativeDuration:frameDuration animations:^{
view.transform = CGAffineTransformMakeTranslation(-2, 0);
}];
[UIView addKeyframeWithRelativeStartTime:3*frameDuration relativeDuration:frameDuration animations:^{
view.transform = CGAffineTransformMakeTranslation(0, 0);
}];
} completion:nil];
我覺得這兩個動畫應該是相同的,但是他們沒有。我在做什麼錯了?
編輯:Example project(使用命令+ T切換在模擬器慢動畫)
「但是,它們不是。」你能詳細說明嗎?他們有什麼不同? –
對不起,我真的應該添加一個我現在添加的示例項目。關鍵幀的時間點不匹配。另外:哇,大衛Rönnqvist!你的[Clear * Animation Code post](http://ronnqvi.st/clear-animation-code/)是我發佈這個問題的原因! – iMaddin