在RN 項(xiàng)目啟動(dòng)之后有一個(gè)短暫的白屏,調(diào)試階段白屏的時(shí)間較長(zhǎng),大概3-5秒,打正式包后這個(gè)白屏?xí)r間會(huì)大大縮短,大多時(shí)候都是一閃而過,所以稱之為“閃白”。
其實(shí)解決的方案也有很多,這里做一個(gè)簡(jiǎn)單的總結(jié)。
白屏的原因
在iOS App 中有 啟動(dòng)圖(LaunchImage),啟動(dòng)圖結(jié)束后才會(huì)出現(xiàn)上述的閃白,這個(gè)過程是 js 解釋的過程,JS 解釋完畢之前沒有內(nèi)容,所以才表現(xiàn)出白屏,那么解決的方法就是在啟動(dòng)圖結(jié)束后,JS 解釋完成前做一些簡(jiǎn)單的處理。
解決的常見方案:
代碼實(shí)現(xiàn)
新建一個(gè)SplashScreen 文件用來接收 JS 發(fā)來的”移除占位圖”的消息。相關(guān)代碼如下:
SplashScreen.h
#import <Foundation/Foundation.h> #import "RCTBridgeModule.h" @interface SplashScreen : NSObject<RCTBridgeModule> @end
SplashScreen.m
#import "SplashScreen.h" @implementation SplashScreen RCT_EXPORT_MODULE(); RCT_EXPORT_METHOD(close){ [[NSNotificationCenter defaultCenter] postNotificationName:@"Notification_CLOSE_SPLASH_SCREEN" object:nil]; } @end
在AppDelegate.m 加入以下代碼:
@interface AppDelegate () { UIImageView *splashImage; } @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(closeSplashImage) name:"Notification_CLOSE_SPLASH_SCREEN" object:nil]; ... [self autoSplashScreen];//寫在 return YES 之前,其他代碼之后 return YES; } -(void)autoSplashScreen { if (!splashImage) { splashImage = [[UIImageView alloc]initWithFrame:[UIScreen mainScreen].bounds]; } if (IPHONESCREEN3p5) { [splashImage setImage:[UIImage imageNamed:@"launch4"]]; }else if (IPHONESCREEN4){ [splashImage setImage:[UIImage imageNamed:@"launch5"]]; }else if (IPHONESCREEN4p7){ [splashImage setImage:[UIImage imageNamed:@"launch6"]]; }else if (IPHONESCREEN5p5){ [splashImage setImage:[UIImage imageNamed:@"launch7"]]; } [self.window addSubview:splashImage]; } -(void)closeSplashImage { dispatch_sync(dispatch_get_main_queue(), ^{ [UIView animateWithDuration:0.5 animations:^{ splashImage.alpha = 0; } completion:^(BOOL finished){ [splashImage removeFromSuperview]; }]; }); }
在合適的時(shí)機(jī)選擇移除占位圖。js端代碼:
if (Platform.OS === 'ios') { NativeModules.SplashScreen.close(); };
更加詳細(xì)的信息可以訪問:https://github.com/crazycodeboy/react-native-splash-screen/blob/master/README.zh.md
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:0731-84117792 E-MAIL:11247931@qq.com