本文分享一個簡單的倒計時動畫效果,透過遞迴呼叫搭配 UIView 動畫,讓數字在每次倒數時呈現淡出並縮小的視覺效果。
-(void)countDown:(int)count {
if (count <= 0) {
// 倒計時已到,在這裡處理需要執行的動作
return;
}
UILabel* lblCountDown = [[UILabel alloc] initWithFrame:CGRectMake(260, 120, 50, 50)];
lblCountDown.textColor = [UIColor redColor];
lblCountDown.font = [UIFont boldSystemFontOfSize:66];
lblCountDown.backgroundColor = [UIColor clearColor];
lblCountDown.text = [NSString stringWithFormat:@"%d", _SettedCountDown];
[self.view addSubview:lblCountDown];
[UIView animateWithDuration:1
delay:0
options:UIViewAnimationCurveEaseOut
animations:^{
lblCountDown.alpha = 0;
lblCountDown.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.5, 0.5);
}
completion:^(BOOL finished) {
[lblCountDown removeFromSuperview];
// 遞迴呼叫,直到計時為零
[self countDown:count - 1];
}];
}
這個範例的關鍵在於:每次顯示一個數字標籤後,透過動畫讓它在一秒內逐漸透明並縮小,動畫結束後移除該標籤,再遞迴呼叫自身處理下一個數字,直到倒數歸零為止。這種做法能帶來流暢且富有層次感的倒數視覺體驗,很適合用於遊戲開始前的準備倒數等場景。