Как оживить CABasicAnimation в фоновом режиме после нажатия кнопки "домой"?
Я новичок в разработке ios. Я использую образы колес в моем проекте. Анимация отлично работает в режиме переднего плана. После этого я нажал кнопку home.Now, я перезапустил приложение, анимация колеса не работает. это мой код:
CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"]; animation.fromValue = [NSNumber numberWithFloat:0.0f];
animation.toValue = [NSNumber numberWithFloat: 2*M_PI];
animation.duration = 1.0f;
animation.repeatCount = INFINITY;
[imageLeft.layer addAnimation:animation forKey:@"SpinAnimation"];
Ответы
Ответ 1
Попробуйте это,
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addAnimation:) name:UIApplicationWillEnterForegroundNotification object:nil];
}
- (void)addAnimation:(NSNotification *)notificaiton
{
CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
animation.fromValue = [NSNumber numberWithFloat: 2*M_PI];
animation.toValue = [NSNumber numberWithFloat:0.0f];
animation.duration = 4.0f;
animation.repeatCount = INFINITY;
[imageLeft.layer addAnimation:animation forKey:@"SpinAnimation"];
[imageRight.layer addAnimation:animation forKey:@"SpinAnimation"];
}
Ответ 2
Swift 4.2 Обновлено
Ах, я понял это - используйте это, и все случаи, такие как остановка после перехода в фон, будут исправлены.
animation.isRemovedOnCompletion = false
Ответ 3
Попробуйте это,
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addAnimation:) name:UIApplicationWillEnterForegroundNotification object:nil];
}
- (void)addAnimation:(NSNotification *)notificaiton
{
CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
animation.fromValue = [NSNumber numberWithFloat: 2*M_PI];
animation.toValue = [NSNumber numberWithFloat:0.0f];
animation.duration = 4.0f;
animation.repeatCount = INFINITY;
[imageLeft.layer addAnimation:animation forKey:@"SpinAnimation"];
[imageRight.layer addAnimation:animation forKey:@"SpinAnimation"];
}
Ответ 4
Когда вы покидаете приложение, все анимации удаляются со своих слоев: система вызывает removeAllAnimations на каждом слое. Поэтому, если вы хотите продолжить анимацию, вы можете прослушать UIApplicationDidBecomeActiveNotification и снова запустить анимацию.
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
if (![_imageLeft.layer animationForKey:@"SpinAnimation"])
{
CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
animation.fromValue = [NSNumber numberWithFloat: 2*M_PI];
animation.toValue = [NSNumber numberWithFloat:0.0f];
animation.duration = 4.0f;
animation.repeatCount = INFINITY;
[_imageLeft.layer addAnimation:animation forKey:@"SpinAnimation"];
}
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addAnimation:) name:UIApplicationDidBecomeActiveNotification object:nil];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)addAnimation:(NSNotification *)notificaiton
{
if (_imageLeft && ![_imageLeft.layer animationForKey:@"SpinAnimation"])
{
CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
animation.fromValue = [NSNumber numberWithFloat: 2*M_PI];
animation.toValue = [NSNumber numberWithFloat:0.0f];
animation.duration = 4.0f;
animation.repeatCount = INFINITY;
[_imageLeft.layer addAnimation:animation forKey:@"SpinAnimation"];
}
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
Ответ 5
Когда приложение переходит в фоновый режим, система удаляет все анимации из своих слоев. В вашем методе viewWillAppear:
зарегистрируйтесь для UIApplicationDidBecomeActiveNotification
. Когда вы заметите уведомление, добавьте анимацию еще раз. Отмените регистрацию для уведомления в viewWillDisappear:
.
Ответ 6
Обычно работает кодирование следующим образом:
animation.fillMode = CAMediaTimingFillMode.forwards
animation.isRemovedOnCompletion = false
Но, если это не сработало, как ожидалось, вы можете пропустить некоторый код:
animation.beginTime = CACurrentMediaTime()