简体   繁体   中英

How to get UILabel to fade text in & out with CATransition?

I'm trying to get a AM/PM lane to fade in & out, but I can't seem to get it to work both ways.

If I only use one it works, but when I try to add two, it just flips back and forth without the proper fade animation.

Can anyone give me some insight on why, and how to fix this?

Heres my code below.

- (void)setState:(MonringNightLabelState)state animated:(BOOL)animated {

    CATransition *animationAM = [CATransition animation];
    animationAM.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animationAM.type = kCATransitionFade;
    animationAM.duration = 0.3;

    CATransition *animationPM = [CATransition animation];
    animationPM.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animationPM.type = kCATransitionFade;
    animationPM.duration = 0.3;

    if (animated)
    {
        [UIView animateWithDuration:0.3
                              delay:0.0
                            options:UIViewAnimationOptionBeginFromCurrentState
                         animations:^{
                             [self setState:state animated:NO];
                         }
                         completion:^(BOOL finished) {

                         }];
    }

    switch (state)
    {
        case MorningNightLabelStateAM:
        {
            [self.morningNightLabel.layer addAnimation:animationAM forKey:@"kCATransitionFade"];

            self.morningNightLabel.text = @"AM";

        }
            break;
        case MorningNightLabelStatePM:
        {
            [self.morningNightLabel.layer addAnimation:animationPM forKey:@"kCATransitionFade"];

            self.morningNightLabel.text = @"PM";
        }
            break;
    }
}

This is the way I fixed it in swift:

var transitionAnimation = CATransition()
transitionAnimation.type = kCATransitionFade
transitionAnimation.duration = 0.2
transitionAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
transitionAnimation.fillMode = kCAFillModeBoth
self.titleLabel.layer.addAnimation(transitionAnimation, forKey: "fadeAnimation")
self.titleLabel.text = newTitle

which is working for me.

Probably this should be enough:

CATransition *animationPM = [CATransition animation];
animationPM.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
animationPM.type = kCATransitionFade;
animationPM.duration = 0.3;
[self.morningNightLabel.layer addAnimation:animationAM forKey:@"kCATransitionFade"];
self.morningNightLabel.text = (state == MorningNightLabelStateAM) ? @"AM" : @"PM";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM