【发布时间】:2020-07-30 11:22:05
【问题描述】:
我有一个我认为非常简单的动画案例。有一个视图位于 0 alpha 除非它变为 1 直到具有一种类型事件的未来动画,或者在几秒钟内变为 1 具有另一种类型的事件。我的问题是,当连续调用这两个事件时,实际上会运行以下代码:
[UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^(void){
self->bkgView.alpha = 1.0;
} completion:^(BOOL finished){}];
[UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^(void){
self->bkgView.alpha = 1.0;
} completion:^(BOOL finished){
NSLog(@"completion finished: %d", finished);
if (finished)
[UIView animateWithDuration:0.5 delay:3 options:UIViewAnimationOptionBeginFromCurrentState animations:^(void){
self->bkgView.alpha = 0;
} completion:^(BOOL finished){}];
}];
我认为第二个调用只是取消了第一个调用并从该调用的任何位置接管,因此我将闪烁到 alpha 1 几秒钟。实际发生的根本不是动画,完成块被立即调用,完成为真 - 所以没有迹象表明它被取消了。我想我应该问,而不是在这个看似微不足道的案例上猛烈抨击,我做错了什么?
编辑:当我说代码微不足道时,我的意思是,但如果你想尝试的话,这里是整个视图控制器,你可以放在一个新的单视图项目上:
#import "ViewController.h"
@interface ViewController () {
UIView *bkgView;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
CGFloat x = 20;;
for (NSString *str in @[@"show", @"flash", @"both"]) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:NSSelectorFromString(str) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:str forState:UIControlStateNormal];
button.backgroundColor = [UIColor grayColor];
button.frame = CGRectMake(x, 100, 80, 40);
[self.view addSubview:button];
x += 100;
}
bkgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 100)];
bkgView.backgroundColor = [UIColor blackColor];
bkgView.alpha = 0;
[self.view addSubview:bkgView];
}
-(void)both {
[self show];
[self flash];
}
-(void)show {
[UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^(void){
self->bkgView.alpha = 1.0;
} completion:^(BOOL finished){}];
}
-(void)flash {
[UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^(void){
self->bkgView.alpha = 1.0;
} completion:^(BOOL finished){
[UIView animateWithDuration:0.5 delay:3 options:UIViewAnimationOptionBeginFromCurrentState animations:^(void){
self->bkgView.alpha = 0;
} completion:^(BOOL finished){}];
}];
}
它加载了三个按钮。如果单击“显示”,它会淡出一个矩形。如果单击“闪烁”,它会在矩形中淡出 3 秒钟,然后淡出。我的问题是,如果您单击“两者”,这在这个简单的示例中可能没有多大意义,但会模拟连续调用 show 和 flash 动作,这可能在我的原始代码中发生。我希望它的行为与“flash”相同(因为它应该立即从“show”函数中接管),但它什么也不做,矩形没有显示。
【问题讨论】:
-
很难用你的描述和你发布的代码说。尝试拼凑一个minimal reproducible example。
-
@DonMag MRE 添加。
-
好的 - 不完全清楚你想要做什么。对于此示例,在点击显示时,您希望黑色视图“淡入”...等待 3 秒...然后淡出?如果我快速点击两次会发生什么?在任何 alpha 处停止“淡入”,然后等待 3 并淡出?如果我点击,让它淡入,然后点击在 3 秒内立即淡出?
-
您可以定义两个 CABasicAnimation 并将它们与animationKeys 应用到一个CALayer *bkgLayer 或bkgView.layer 由sender 或在init 或viewDidLoad 调用。目前,您定义了一个淡入淡出的块并定义了一个空块,该空块被一个覆盖第一个块的块覆盖,并调用一个将淡出并调用空的第五个块。在 CABasicAnimation 的帮助下,您的代码看起来会更容易。
-
@DonMag,我把这个例子讲得更清楚了。
标签: objective-c core-graphics objective-c-blocks uiviewanimation