在我的Xcode项目中,我在xib上放了一个标签。
我想连续淡入和淡出标签,直到用户点击屏幕。发生这种情况时,我想要一个新视图出现。
有人可以建议如何进行淡入/淡出吗?
答案 0 :(得分:7)
您可以使用选项对UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat
来告诉Core Animation您希望标签连续淡入和淡出。
- (void)startAnimatingLabel
{
self.label.alpha = 0;
[UIView animateWithDuration:1
delay:0
options: UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat
animations:^{
self.label.alpha = 1;
} completion:nil];
}
要停止播放动画,只需将其从标签的图层中删除即可。
- (IBAction)tap:(UITapGestureRecognizer *)sender
{
[self.label.layer removeAllAnimations];
self.label.alpha = 0;
[self presentNewView];
}
编辑:不太突然的完成方式是从当前视图状态动画到最后一个(这将中断当前的重复动画)。
- (IBAction)tap:(UITapGestureRecognizer *)sender
{
[UIView animateWithDuration:1
delay:0
options:UIViewAnimationOptionBeginFromCurrentState
animations:^{
self.label.alpha = 0;
} completion:^(BOOL finished){
[self presentNewView];
}];
}
答案 1 :(得分:5)
您可以在循环中放置一对链式动画,或者每次调用一个包含链式动画的函数,直到遇到用户点击。
通过链式动画,我的意思是这样的(你可以设置动画持续时间以满足你的需要):
myLabel.alpha = 0.0;
[UIView animateWithDuration:1.0
delay:0.0
options: UIViewAnimationCurveEaseOut
animations:^{
myLabel.alpha = 1.0;
}
completion:^(BOOL finished){
[UIView animateWithDuration:1.0
delay:1.0
options: UIViewAnimationCurveEaseOut
animations:^{
myLabel.alpha = 0.0;
}
completion:^(BOOL finished){
NSLog(@"Done!");
}];
}];
上面的代码首先会淡化您的标签,然后将其淡出。你可以把它放在一个函数中并调用它,直到你遇到用户点击。
答案 2 :(得分:1)
创建CABasicAnimation
并将其添加到您的标签:
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
animation.fromValue = @(1.0f);
animation.toValue = @(0.1f);
animation.repeatCount = INFINITY;
animation.duration = 0.75;
animation.autoreverses = YES;
[label.layer addAnimation:animation];
当您点击按钮时,只需获取指向该标签的指针并删除所有动画:
[label.layer removeAllAnimations];
答案 3 :(得分:0)
尝试此操作,如果您用重复次数替换 INFINITY ,则可以管理动画重复次数
fadingLabel.alpha = 1.0;
[UIView beginAnimations:@"fadingLabel" context:nil];
[UIView setAnimationDuration:4.0];
[UIView setAnimationRepeatCount:INFINITY];
fadingLabel.alpha = 0.0;
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView commitAnimations];
答案 4 :(得分:0)
Wayne Hartman's Answer在Swift 4中
let animation = CABasicAnimation(keyPath: "opacity")
animation.fromValue = 1
animation.toValue = 0.1
animation.duration = 0.75
animation.repeatCount = .infinity
animation.autoreverses = true
label.layer.add(animation, forKey: nil)
和
label.layer.removeAllAnimations()