在UILabel中的文本之间淡入淡出

时间:2014-11-02 19:39:28

标签: ios objective-c cocoa-touch uilabel uiviewanimation

我希望为UILabel的文本设置动画,以便它显示一个文本几秒钟,然后淡入默认文本。

我目前正在使用以下代码:

-(void)tapOnBalance:(id)sender{
      [UIView animateWithDuration:1.0 delay:0.0 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
        cell.amountLabel.text = @"Hola!";
      } completion:nil];

      // Pause the function - act as a 'delay'
      [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:3]];

      [UIView animateWithDuration:1.0 delay:0.0 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
        cell.amountLabel.text = @"Hallo!";
      } completion:nil];

}

这样可行,但[NSRunLoop currentRunLoop]暂停整个应用,阻止所有内容持续3秒。

如何摆脱主线程上的阻塞并仍然得到相同的结果?

1 个答案:

答案 0 :(得分:1)

简单的淡入淡出(不是交叉渐变)可以是这样的:

// change a label's text after some delay by fading
// out, changing the text, then fading back in
- (void)fadeLabel:(UILabel *)label toText:(NSString *)toText completion:(void (^)(BOOL))completion {
    [UIView animateWithDuration:0.2 delay:0.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        label.alpha = 0.0;
    } completion:^(BOOL finished) {
        label.text = toText;
        [UIView animateWithDuration:0.2 delay:0.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
            label.alpha = 1.0;
        } completion:completion];
    }];
}

// simpler signature that can be done on a perform
- (void)changeLabelText:(NSString *)toText {
    [self fadeLabel:self.myLabel toText:toText completion:nil];
}

// set the label to something, then change it with a fade, then change it back
self.myLabel.text = @"text";
[self performSelector:@selector(changeLabelText:) withObject:@"hola!" afterDelay:4];
[self performSelector:@selector(changeLabelText:) withObject:@"text" afterDelay:8];

您还可以嵌套调用的完成块(并添加延迟参数),以便在没有执行的情况下执行类似的操作。要进行交叉淡入淡出,请使用两个标签(具有相同的帧)的类似技术,其中一个的alpha为零,另一个的alpha为1。