iOS开发 适配iPhoneX/iPhoneXr/iPhoneXs/iPhonexs max

1、写个单例

/**
.h文件
*/
@interface Singleton : NSObject
+(instancetype) shareInstance ;
@property (nonatomic, assign) CGFloat SafeAreaTopHeightX;//
@property (nonatomic, assign) CGFloat kStatusBarHeightX;//
@property (nonatomic, assign) CGFloat SafeAreaBottomHeightX;//
@end
/**
.m文件
*/
#import "Singleton.h"
static Singleton* _instance = nil;
@implementation Singleton
+(instancetype) shareInstance
{
 static dispatch_once_t onceToken ;
 dispatch_once(&onceToken, ^{
 _instance = [[self alloc] init] ;
 }) ;
 
 return _instance ;
}
@end

2、在AppDelegate.m文件中

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
 self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
 self.window.backgroundColor = [UIColor whiteColor];
 [self.window makeKeyAndVisible];
//必须写在这个位置,在window初始化完成时
 if (isIPhoneX()==1) {
 [Singleton shareInstance].SafeAreaTopHeightX = 88.0f;
 [Singleton shareInstance].SafeAreaBottomHeightX = 34.0f;
 [Singleton shareInstance].kStatusBarHeightX = 44.0f ;
 
 }else{
 [Singleton shareInstance].SafeAreaTopHeightX = 64.0f;
 [Singleton shareInstance].SafeAreaBottomHeightX = 0;
 [Singleton shareInstance].kStatusBarHeightX = 20.0f ;
 }
 
#pragma mark - 默认加载UI
 LoginController *loginVC = [[LoginController alloc] init];
 self.window.rootViewController = loginVC;
 self.window.rootViewController = mainVC;
 
 
 return YES;
}
static inline BOOL isIPhoneX() {
 BOOL iPhoneX = NO;
 /// 先判断设备是否是iPhone/iPod
 if (UIDevice.currentDevice.userInterfaceIdiom != UIUserInterfaceIdiomPhone) {
 return iPhoneX;
 }
 
 if (@available(iOS 11.0, *)) {
 /// 利用safeAreaInsets.bottom > 0.0来判断是否是iPhone X。
 UIWindow *mainWindow = [[[UIApplication sharedApplication] delegate] window];
 if (mainWindow.safeAreaInsets.bottom > 0.0) {
 iPhoneX = YES;
 }
 }
 
 return iPhoneX;
}

3、在.pch文件中 ,这样定义宏

//导航栏高度
#define SafeAreaTopHeight [Singleton shareInstance].SafeAreaTopHeightX
//状态栏
#define kStatusBarHeight [Singleton shareInstance].kStatusBarHeightX
//底部宏
#define SafeAreaBottomHeight [Singleton shareInstance].SafeAreaBottomHeightX

iOS开发 适配iPhoneX/iPhoneXr/iPhoneXs/iPhonexs max

相关推荐