淡入/淡出文本动画

3
我正在使用NSTimer(5秒持续时间)和选择器,从NSArray中随机选择姓名。
以下是一些代码:

....

NSDate *endtime = [NSDate dateWithTimeIntervalSinceNow:5];

    [NSTimer scheduledTimerWithTimeInterval:0.2 
                                     target:self 
                                   selector:@selector(selectPlayer:) 
                                   userInfo:endtime 
                                    repeats:YES ];

...

-(void)selectPlayer:(NSTimer *)timer
{
    if ([timer.userInfo timeIntervalSinceNow] < 0) 
    {
        [timer invalidate];
    }

    NSString *playerName = [[NSString alloc]initWithFormat:@"%@", 
                            [self.playersNames objectAtIndex:random() & [self.playersNames count]-1]];


    self.playersLabel.text = playerName;
    [playerName release]; 
}

那段代码完美运行。self.playersLabel会每0.2秒填充一个随机名称。

我想要的是在playersLabel中更改名称时添加一些淡入/淡出动画效果。

如何实现?

2个回答

8

您可以使用此功能来设置文本:

    [UIView animateWithDuration:0.4 animations:^{
        self.playersLabel.alpha = 0;
    } completion:^(BOOL finished) {
        self.playersLabel.text = @"Other text";
        [UIView animateWithDuration:0.4 animations:^{
            self.playersLabel.alpha = 1;
        }];
    }];

如果字符串比UILabel字段长,是否可以使用相同的动画使NSString在UILabel中进行过渡? - valbu17

1

当你改变playersLabel的文本时,只需添加一个动画即可。

以下是实现此目标的方法:

        [UIView animateWithDuration:0.1 delay:0.f options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         playersLabel.alpha = 0.f;
                     } completion:^(BOOL complete){ 
                         [UIView animateWithDuration:0.1 delay:0.f options:UIViewAnimationOptionCurveEaseInOut
                                          animations:^{  
                                            playersLabel.text = playerName;
                                            playersLabel.alpha = 1.f;
                                          } completion:NULL];
                     }];

我使用第一个动画的完成块来重置标签的alpha值。每个动画持续0.1秒,因为您的playerName每0.2秒选择一次(0.1*2)。您可以使用UIViewAnimationOptionAutoreverse,但是如果我记得正确,它不会重置标签的alpha属性。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接