我有这个代码:
-(void)animationLoop{
CGPoint oldPoint = CGPointMake(myCircleUIView.frame.origin.x, myCircleUIView.frame.origin.y);
[UIView animateWithDuration:1.0
animations: ^{ myCircleUIView.frame = CGRectMake(myCircleUIView.frame.origin.x + [self randomFloatingGenerator], myCircleUIView.frame.origin.y + [self randomFloatingGenerator], myCircleUIView.frame.size.width, myCircleUIView.frame.size.height); }
completion:
^(BOOL finished) {
[UIView animateWithDuration:1.0
animations:^{ myCircleUIView.frame = CGRectMake(oldPoint.x, oldPoint.y, myCircleUIView.frame.size.width, myCircleUIView.frame.size.height);}
completion:
^(BOOL finished) {[self animationLoop];}];
}];
}
但是我试图在与它交互时停止动画,但是[myCircleUIView.layer removeAllAnimations];
不会做任何建议吗?
答案 0 :(得分:3)
当您使用CALayer's
-removeAllAnimations
停止动画时,将使用finished == NO
调用回调。所以改变你的动画代码如下:
- (void)animationLoop {
__weak id weakSelf = self;
CGPoint oldPoint = CGPointMake(myCircleUIView.frame.origin.x, myCircleUIView.frame.origin.y);
[UIView animateWithDuration:1.0
animations:^{
myCircleUIView.frame = CGRectMake(myCircleUIView.frame.origin.x + [weakSelf randomFloatingGenerator], myCircleUIView.frame.origin.y + [weakSelf randomFloatingGenerator], myCircleUIView.frame.size.width, myCircleUIView.frame.size.height);
}
completion:^(BOOL finished) {
if (!finished) return;
[UIView animateWithDuration:1.0
animations:^{
myCircleUIView.frame = CGRectMake(oldPoint.x, oldPoint.y, myCircleUIView.frame.size.width, myCircleUIView.frame.size.height);
}
completion:^(BOOL finished) {
if (!finished) return;
[weakSelf animationLoop];
}];
}];
}
我还建议你不要将对self
的强引用传递给复制到堆的块,如果你真的不想因为可能retain cycle
。
答案 1 :(得分:0)
在你的循环中添加bool并在需要停止动画时设置为false,如下面的代码所示......
BOOL IsAnimationContinue=true;
-(void)animationLoop{
CGPoint oldPoint = CGPointMake(myCircleUIView.frame.origin.x, myCircleUIView.frame.origin.y);
[UIView animateWithDuration:1.0
animations: ^{
if(IsAnimationContinue)
{
myCircleUIView.frame = CGRectMake(myCircleUIView.frame.origin.x + [self randomFloatingGenerator], myCircleUIView.frame.origin.y + [self randomFloatingGenerator], myCircleUIView.frame.size.width, myCircleUIView.frame.size.height);
}}
completion:^(BOOL finished) {
[UIView animateWithDuration:1.0
animations:^{
if(IsAnimationContinue)
{
myCircleUIView.frame = CGRectMake(oldPoint.x, oldPoint.y, myCircleUIView.frame.size.width, myCircleUIView.frame.size.height);
}}
completion:
^(BOOL finished) {[self animationLoop];}];
}]; }
只需设置
IsAnimationContinue=False
停止动画