我想为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秒钟。

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

最佳答案

一个简单的淡入淡出(而不是交叉淡入淡出)可以像这样:

// 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为一。

关于ios - 延迟在UILabel中的文本之间淡入淡出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26703501/

10-13 01:09