2012-03-06 141 views
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]; 
} 

該代碼工作pefectly。 self.playersLabel每0.2秒填充一個隨機名稱。

我想要的是添加一些fadein/fadeout動畫效果,同時在playersLabel中更改名稱。

如何實現這一目標?

回答

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; 
     }]; 
    }]; 
+0

很可愛。謝謝! – 2013-02-26 17:31:13

+0

如果字符串比UILabel字段長,是否可以使用相同的動畫使NSString在UILabel中進行轉換.. ??? – NorthBlast 2014-06-17 06:00:45

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屬性。

+0

非常感謝你的好友! – foho 2012-03-06 14:00:34