啟動畫面(Splash Screen)停留太久會讓人覺得 App 遲鈍,完全不顯示又顯得生硬。一個常見又低成本的做法,是让啟動圖在進入主介面前先放大並淡出,形成一段自然的過場動畫。以下是在 AppDelegate 中實作的完整寫法。
整體流程可以拆成四件事:建立視窗、隱藏系統狀態列、把啟動圖鋪在視窗上、然後用動畫讓它縮小淡出,動畫結束後移除啟動圖並掛上真正的根視圖控制器。
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[UIApplication sharedApplication].statusBarHidden = YES;
// 1. 建立鋪滿整個視窗的啟動圖
UIImageView *splashScreen = [[UIImageView alloc] initWithFrame:self.window.bounds];
splashScreen.image = [UIImage imageNamed:@"程序進入圖.png"];
[self.window addSubview:splashScreen];
// 2. 縮小 + 淡出,5 秒後收尾
[UIView animateWithDuration:5.0 animations:^{
CATransform3D transform = CATransform3DMakeScale(0.5, 0.5, 1.0);
splashScreen.layer.transform = transform;
splashScreen.alpha = 0.8;
MyLog(@"111");
} completion:^(BOOL finished) {
[splashScreen removeFromSuperview];
MyLog(@"222");
self.window.rootViewController = [[LoginViewController alloc] init];
self.window.backgroundColor = [UIColor whiteColor];
}];
_netRequest = [[NetRequest alloc] init];
[self.window makeKeyAndVisible];
return YES;
}
動畫秒數:範例中的 5.0 秒其實偏長,使用者會等得不耐煩。實務上 0.3~0.8 秒的手感最好,若要掩護初始化時間,應該把動畫與網路請求「並行」跑,而不是硬等動畫結束。
alpha 值:動畫終值是 0.8 而非 0,所以視覺上是「淡到還看得見」就瞬間消失。若要真正淡出,把終值設為 0 並在 completion 中移除,過渡會更順。
不要忘了 makeKeyAndVisible:如果這行放在動畫之後才呼叫,啟動畫面會先黑一下才出現。範例把它放在最後是刻意的,視窗必須先成為 Key Window,動畫才有意義。
與真實啟動圖搭配:iOS 的 LaunchScreen 是系統層級的資源,會在 didFinishLaunchingWithOptions 之前顯示。如果自製的啟動圖與 LaunchScreen 視覺一致,銜接起來幾乎看不出接縫,效果會比單純做動畫好很多。