進行中のアニメーションを変更する方法がわかりません。
これは、あなたが望むことをすると思うコードです。増加/減少ボタンを使用して ivar を変更しanimationDuration
、アニメーションを 2 つの半分 (前方半分と後方半分) として手動でループします。新しいアニメーション (順方向または逆方向) が開始animationDuration
されるたびに、その時点での値が取得されるため、短いアニメーションの場合、ほとんど瞬時に変化するように見えます。ただし、実際にはアニメーションの最大/最小ポイントでアニメーション速度を変更するだけなので、長時間のアニメーションではうまく機能しません。
より頻繁に更新したい場合は、アニメーションをさらに小さく分割できます。たとえば、2 つではなく 4 つに分割します (1 -> 1.5、1.5 -> 2.0、2.0 -> 1.5、1.5 -> 1.0)。それが必要。
ヘッダー (MyViewController.h):
// Define some constants to be edited to suit our needs
#define kAnimationDurationMin 0.1
#define kAnimationDurationDefault 0.4
#define kAnimationDurationMax 2.0
#define kAnimationDurationStep 0.05
@interface MyViewController : UIViewController {
// The variable to store the target animation duration in
double animationDuration;
// Whether the next animation should be a reverse animation or not
BOOL reverse;
// The view to be animated, this should be connected in Interface Builder
IBOutlet UIView *ball;
}
//The method to actually do the animation
-(void)doAnimation;
// These 2 methods should be connected to the 'touch up inside' event of the relevant buttons in Interface Builder
- (IBAction)incButtonPressed:(id)sender;
- (IBAction)decButtonPressed:(id)sender;
@end
実装 (MyViewController.m):
#import "MyViewController.h"
@implementation MyViewController
-(void)viewDidLoad {
// If animation duration has not yet been set (it will be zero) then set it to the default.
if (animationDuration < kAnimationDurationMin) animationDuration = kAnimationDurationDefault;
// Start the animation
[self doAnimation];
}
// This method does the animation
-(void)doAnimation {
[UIView beginAnimations:@"ball" context:NULL];
[UIView setAnimationDuration: animationDuration];
[UIView setAnimationCurve: UIViewAnimationCurveEaseInOut];
// Do not repeat
[UIView setAnimationRepeatCount: 0];
// Not autoreversing allows us to trigger the animationDuration change twice as frequently.
[UIView setAnimationRepeatAutoreverses:NO];
// When the animation is complete, start it again by calling [self doAnimation];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(doAnimation)];
if (reverse) {
// Reset to default
ball.transform = CGAffineTransformMakeScale(1,1);
} else {
// Target of forward animation
ball.transform = CGAffineTransformMakeScale(2,2);
}
// Toggle reverse
reverse = !reverse;
[UIView commitAnimations];
}
- (IBAction)incButtonPressed:(id)sender {
animationDuration += kAnimationDurationStep;
if (animationDuration > kAnimationDurationMax) animationDuration = kAnimationDurationMax;
}
- (IBAction)decButtonPressed:(id)sender {
animationDuration -= kAnimationDurationStep;
if (animationDuration < kAnimationDurationMin) animationDuration = kAnimationDurationMin;
}
@end