在RN 项目启动之后有一个短暂的白屏,调试阶段白屏的时间较长,大概3-5秒,打正式包后这个白屏时间会大大缩短,大多时候都是一闪而过,所以称之为“闪白”。
其实解决的方案也有很多,这里做一个简单的总结。
白屏的原因
在iOS App 中有 启动图(LaunchImage),启动图结束后才会出现上述的闪白,这个过程是 js 解释的过程,JS 解释完毕之前没有内容,所以才表现出白屏,那么解决的方法就是在启动图结束后,JS 解释完成前做一些简单的处理。
解决的常见方案:
代码实现
新建一个SplashScreen 文件用来接收 JS 发来的”移除占位图”的消息。相关代码如下:
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];
- }];
- });
- }
在合适的时机选择移除占位图。js端代码:
- if (Platform.OS === 'ios') {
- NativeModules.SplashScreen.close();
- };
更加详细的信息可以访问:https://github.com/crazycodeboy/react-native-splash-screen/blob/master/README.zh.md
来源: http://www.jb51.net/article/120594.htm