简体   繁体   中英

UILabel: multiple lines of text animation fade line by line

for example:

label.text = @"I \n love \n stackoverflow ";

how to show those three lines just like first animation fade show "I" , then after animation during time animation fade show "love" finally after animation during time animation fade show "stackoverflow"?

I have created a function for your request. Make sure your label have dynamic height, numberOfLines = 0 and try it ;)

- (void)animateLabel:(UILabel*)label withString:(NSString*)string duration:(NSTimeInterval)duration {
  NSUInteger length = [string length];
  NSUInteger paraStart = 0, paraEnd = 0, contentsEnd = 0;
  NSMutableArray *displayedStringArray = [NSMutableArray array];
  NSRange currentRange;

  while (paraEnd < length) {
    [string getParagraphStart:&paraStart end:&paraEnd
              contentsEnd:&contentsEnd forRange:NSMakeRange(paraEnd, 0)];
    currentRange = NSMakeRange(0, contentsEnd);
    [displayedStringArray addObject:[string substringWithRange:currentRange]];
  }


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

  __block void (^animationBlock) (int lineNumber);
  __block void (^weakAnimationBlock) (int lineNumber);
  animationBlock = ^void(int lineNumber){
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
      [label.layer addAnimation:animation forKey:@"changeTextTransition"];
      label.text = displayedStringArray[lineNumber];

      weakAnimationBlock = animationBlock;
      __block int nextLine = lineNumber + 1;

      if (nextLine < displayedStringArray.count) {
        weakAnimationBlock(nextLine);
      }
    });
  };

  animationBlock(0);
}

Simply call

[YOUR_CLASS animateLabel:label withString:@"I\\nLove\\nStackOverFlow" duration:YOUR_DURATION];]

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