ios 淡入淡出动画

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20891614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 22:57:24  来源:igfitidea点击:

Fade In Fade Out Animation

ioscocoa-touchcore-animation

提问by HiDuEi

Here is some code I struggle with for a while.

这是我挣扎了一段时间的一些代码。

If you start the fade in animation, the label text fades in. If I start the fade out animation the the label text fades out.

如果你开始淡入动画,标签文本淡入。如果我开始淡出动画,标签文本淡出。

When I start the startFademethod, only fade out is shown. How can I wait for the fadeInmethod to finish visually before starting the fadeOutmethod.

当我启动该startFade方法时,只显示淡出。fadeIn在启动该fadeOut方法之前,如何等待该方法在视觉上完成。

-(IBAction)startFade:(id)sender{
    [self fadeIn];
    [self fadeOut];
}

-(IBAction)fadeIn:(id)sender{
    [self fadeIn];
}

-(IBAction)fadeOut:(id)sender{
[self fadeOut];
}

-(void) fadeIn{
    [_label setAlpha:0];
    [UILabel beginAnimations:NULL context:nil];
    [UILabel setAnimationDuration:2.0];
    [_label setAlpha:1];
    [UILabel commitAnimations];
}

-(void) fadeOut{
    [UILabel beginAnimations:NULL context:nil];
    [UILabel setAnimationDuration:2.0];
    [_label setAlpha:0];
    [UILabel commitAnimations];
}

回答by hgwhittle

When you call the fadeInand fadeOutmethods back to back like you're doing, the code is run instantaneously, so you'll only see animation from the last method called. UIView block based animation provides a completion handler, which seems to be exactly what you're looking for. So your code might looks something like this:

当您像正在做的那样背靠背调用fadeInfadeOut方法时,代码会立即运行,因此您只能看到最后调用的方法的动画。基于 UIView 块的动画提供了一个完成处理程序,这似乎正是您正在寻找的。所以你的代码可能看起来像这样:

-(IBAction)startFade:(id)sender {

    [_label setAlpha:0.0f];        

    //fade in
    [UIView animateWithDuration:2.0f animations:^{

        [_label setAlpha:1.0f];

    } completion:^(BOOL finished) {

        //fade out
        [UIView animateWithDuration:2.0f animations:^{

            [_label setAlpha:0.0f];

        } completion:nil];

    }];
}

Swift:

迅速:

@IBAction func startFade(_ sender: AnyObject) {

    label.alpha = 0.0

    // fade in
    UIView.animate(withDuration: 2.0, animations: { 
        label.alpha = 1.0
    }) { (finished) in
        // fade out
        UIView.animate(withDuration: 2.0, animations: {
            label.alpha = 0.0
        })
    }
}

回答by holex

that does the job for you (the _labelis your label);

为您完成工作(这_label是您的标签);

- (IBAction)startFade:(id)sender {
    [_label setAlpha:0.f];

    [UIView animateWithDuration:2.f delay:0.f options:UIViewAnimationOptionCurveEaseIn animations:^{
        [_label setAlpha:1.f];
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:2.f delay:0.f options:UIViewAnimationOptionCurveEaseInOut animations:^{
            [_label setAlpha:0.f];
        } completion:nil];
    }];
}

回答by yazh

Try this..

尝试这个..

// Fade Out

// 淡出

 -(void)fadeOut:(UIView*)viewToDissolve withDuration:(NSTimeInterval)duration   andWait:(NSTimeInterval)wait
{
[UIView beginAnimations: @"Fade Out" context:nil];

// wait for time before begin
[UIView setAnimationDelay:wait];

// druation of animation
[UIView setAnimationDuration:duration];
viewToDissolve.alpha = 0.0;
[UIView commitAnimations];
}

// Fade In

// 淡入

-(void) fadeIn:(UIView*)viewToFadeIn withDuration:(NSTimeInterval)duration andWait:(NSTimeInterval)wait

{
[UIView beginAnimations: @"Fade In" context:nil];

// wait for time before begin
[UIView setAnimationDelay:wait];

    // druation of animation
[UIView setAnimationDuration:duration];
viewToFadeIn.alpha = 1;
[UIView commitAnimations];

}

// Fade in from fade out

// 淡入淡出

-(void) fadeInFromFadeOut: (UIView*)viewToFadeIn withDuration:(NSTimeInterval)duration
{
    viewToFadeIn.hidden=NO;
    [self fadeOut:viewToFadeIn withDuration:1 andWait:0];
    [self fadeIn:viewToFadeIn withDuration:duration andWait:0];

}

// Button operation

// 按钮操作

-(void) buttonClicked :(id)sender
{
   NSLog(@"Button clicked");

// Each button is given a tag
int tag = ((UIButton*)sender).tag;
if (tag ==1)
{
    sprite.alpha  =1;
    [self fadeOut : sprite withDuration: 10 andWait : 1 ];
}
else if (tag ==2)
{
    sprite.alpha  =0;
    [self fadeIn : sprite withDuration: 3 andWait : 1 ];
}
else
{
    [self fadeInFromFadeOut:sprite withDuration:10];
}
}

View this linkto download sample..

查看此链接以下载示例..

Refer this link.

请参阅此链接

Happy to share with you..:-)

很高兴与您分享..:-)

回答by iPhoneDeveloper

Generic answer : You can use this method to apply animation to any UIView object . First create an extension of UIView class . Create a separate swift file and write the code like this

通用答案:您可以使用此方法将动画应用于任何 UIView 对象。首先创建一个 UIView 类的扩展。创建一个单独的swift文件并像这样编写代码

import Foundation
import UIKit

extension UIView {

    func fadeIn() {
        //Swift 2
        UIView.animateWithDuration(1.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: {
            self.alpha = 1.0
        }, completion: nil)

        //Swift 3, 4, 5
        UIView.animate(withDuration: 1.0, delay: 0.0, options: UIView.AnimationOptions.curveEaseIn, animations: {
            self.alpha = 1.0
        }, completion: nil)
    }


    func fadeOut() {
        //Swift 2
        UIView.animateWithDuration(1.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
            self.alpha = 0.0
        }, completion: nil)

        //Swift 3, 4, 5
        UIView.animate(withDuration: 1.0, delay: 0.0, options: UIView.AnimationOptions.curveEaseOut, animations: {
            self.alpha = 0.0
        }, completion: nil)
    }


}

Here self refers to any UIView you refer to . You can use buttons, labels etc to call these 2 methods .

这里 self 指的是你所指的任何 UIView 。您可以使用按钮、标签等来调用这 2 种方法。

Then in any other swift class you can call fadeIn() and fadeOut() like this :

然后在任何其他 swift 类中,您可以像这样调用fadeIn() 和fadeOut():

self.yourUIObject.fadeIn()
self.yourUIObject.fadeOut()

This gives the desired effect of animation to any UIObject .

这为任何 UIObject 提供了所需的动画效果。

回答by Bj?rn Egil

Based on @holex's answer, but simplified a bit (as commented):

基于@holex 的回答,但简化了一点(如评论):

- (IBAction)startFade:(id)sender {
   [_label setAlpha:0.f];

   [UIView animateWithDuration:2.f 
                         delay:0.f 
                       options:UIViewAnimationOptionCurveEaseIn
                             | UIViewAnimationOptionAutoreverse 
                    animations:^{
                                  [_label setAlpha:1.f];
                                } 
                    completion:nil];
}

回答by Julian Król

you can do something like this (check possible parameters values and similar methods here : https://developer.apple.com/library/ios/documentation/uikit/reference/uiview_class/uiview/uiview.html

你可以做这样的事情(在这里检查可能的参数值和类似的方法:https: //developer.apple.com/library/ios/documentation/uikit/reference/uiview_class/uiview/uiview.html

[UIView animateWithDuration:duration
                      delay:delay
                    options:option 
                 animations:^{
                     //fade in here (changing alpha of UILabel component)
                 } 
                 completion:^(BOOL finished){
                    if(finished){
                      //start a fade out here when previous animation is finished (changing alpha of UILabel component)
                 }];
}

回答by jemmons

The easiest way would be to use:

最简单的方法是使用:

[UIView animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion]

and add the fadeOutcall to the completionblock. The documentationmight help answer any questions you have.

并将fadeOut调用添加到completion块。该文档可能有助于回答您的任何问题。

If you can't use the block version for some reason, then you'll have to set a delegate ([UIView setAnimationDelegate:(id)delegate]) and a selector with ([UIView setAnimationDidStopSelector:]) that the delegate will respond to.

如果由于某种原因您不能使用块版本,那么您必须设置一个委托 ( [UIView setAnimationDelegate:(id)delegate]) 和一个带有 ( [UIView setAnimationDidStopSelector:])的选择器,委托将响应。

Again, see the documentationfor more details.

同样,请参阅文档以获取更多详细信息。

回答by Naloiko Eugene

My task was to make a label fade out. And then fade in with changed text. The solution was:

我的任务是让标签淡出。然后用更改的文本淡入。解决方案是:

    -(void)performAnimationOnHistoryButtonLabelUpdatingTextTo:(NSString *)text
{
    [UIView animateWithDuration:0.4f animations:^{
        [self.historyButtonLabel setAlpha:0.0f];

    } completion:^(BOOL finished) {
        self.historyButtonLabel.text = text;

        [UIView animateWithDuration:0.4f animations:^{
            [self.historyButtonLabel setAlpha:1.0f];
        } completion:nil];

    }];
}

回答by Sushree Swagatika

labelAnimate = (UILabel*) [self.view viewWithTag:101];
btnTapMe = (UIButton*) [self.view viewWithTag:100];
[btnTapMe addTarget:self action:@selector(startAnimating:) forControlEvents:UIControlEventTouchUpInside];

//////////////

-(void) startAnimating:(UIButton*)button {
    [labelAnimate setAlpha:0.0];
    [NSTimer scheduledTimerWithTimeInterval:1.8 target:self selector:@selector(continuousEaseInOut) userInfo:button repeats:YES];
}

-(void) continuousFadeInOut {
    [UIView animateWithDuration:2.0 delay:0.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        [labelAnimate setAlpha:1.0];
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:2.0 delay:0.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            [labelAnimate setAlpha:0.0];
        } completion:nil];
    }];
}

回答by joao.arruda

I strongly suggest you use a generic implementation so you can reuse the code whenever you need the fade effect again.

我强烈建议您使用通用实现,以便在您再次需要淡入淡出效果时可以重用代码。

You should create an UIViewextension:

您应该创建一个UIView扩展:

UIView+Animations.h

UIView+Animations.h

#import <Foundation/Foundation.h>

@interface UIView (Animations)

- (void)fadeInWithCompletion:(void (^ __nullable)(BOOL finished))completion;
- (void)fadeOutWithCompletion:(void (^ __nullable)(BOOL finished))completion;;

@end

UIView+Animations.m

UIView+Animations.m

#import "UIView+Animations.h"

@implementation UIView (Animations)

- (void)fadeInWithCompletion:(void (^ __nullable)(BOOL finished))completion {
    [UIView animateWithDuration:2 animations:^{
        [self setAlpha:1];
    } completion:completion];
}

- (void)fadeOutWithCompletion:(void (^ __nullable)(BOOL finished))completion {
    [UIView animateWithDuration:2 animations:^{
        [self setAlpha:0];
    } completion:completion];
}

@end

So, you only have to import the new file to your class or inside your Prefix.pchand use it like this:

因此,您只需将新文件导入您的类或内部Prefix.pch并像这样使用它:

[_label fadeOutWithCompletion:^(BOOL finished) {
   [_label fadeInWithCompletion:nil];
}];

Note that you could also use nilas the completion parameter when you have nothing else to do after completion.

请注意,nil当您在完成后无事可做时,您也可以将其用作完成参数。

I also recommend you do not parameterize the duration to keep a pattern through you entire application.

我还建议您不要参数化持续时间以在整个应用程序中保持模式。

This implementation can be used in the future for UIButton, UILabel, UITextField... Well, any class derived from UIView.

这个实现将来可以用于UIButton, UILabel, UITextField... 好吧,任何从UIView.