IOS 判斷iPhone劉海屏

2020-09-28 11:00:46

現在Apple市場上,越來越流行劉海屏手機(與Android市場一樣,往劉海屏手機方向發展趨勢)。

在iPhone手機角度上看,劉海屏出現在機型較新的手機上(相對較舊/老的iPhone上還沒出現)。

那麼,如何判斷當前的iPhone手機是劉海屏手機呢?同時,如何獲取劉海高度?

在這裡,提供一個工具類:

NotchScreenUtil.h

/*
 * iPhone劉海屏工具類
 */
@interface NotchScreenUtil : NSObject

// 判斷是否是劉海屏
+(BOOL)isIPhoneNotchScreen;

// 獲取劉海屏高度
+(CGFloat)getIPhoneNotchScreenHeight;

@end

NotchScreenUtil.m

#import <Foundation/Foundation.h>
#import "NotchScreenUtil.h"

@implementation NotchScreenUtil

+ (BOOL)isIPhoneNotchScreen{
    BOOL result = NO;
    if (UIDevice.currentDevice.userInterfaceIdiom != UIUserInterfaceIdiomPhone) {
        return result;
    }
    if (@available(iOS 11.0, *)) {
        UIWindow *mainWindow = [[[UIApplication sharedApplication] delegate] window];
        if (mainWindow.safeAreaInsets.bottom > 0.0) {
            result = YES;
        }
    }
    return result;
}

+ (CGFloat)getIPhoneNotchScreenHeight{
    /*
     * iPhone8 Plus  UIEdgeInsets: {20, 0, 0, 0}
     * iPhone8       UIEdgeInsets: {20, 0, 0, 0}
     * iPhone XR     UIEdgeInsets: {44, 0, 34, 0}
     * iPhone XS     UIEdgeInsets: {44, 0, 34, 0}
     * iPhone XS Max UIEdgeInsets: {44, 0, 34, 0}
     */
    CGFloat bottomSpace = 0;
    if (@available(iOS 11.0, *)) {
        UIEdgeInsets safeAreaInsets = UIApplication.sharedApplication.windows.firstObject.safeAreaInsets;
        switch (UIApplication.sharedApplication.statusBarOrientation) {
            case UIInterfaceOrientationPortrait:
            {
                bottomSpace = safeAreaInsets.bottom;
            }
                break;
            case UIInterfaceOrientationLandscapeLeft:
            {
                bottomSpace = safeAreaInsets.right;
            }
                break;
            case UIInterfaceOrientationLandscapeRight:
            {
                bottomSpace = safeAreaInsets.left;
            }
                break;
            case UIInterfaceOrientationPortraitUpsideDown:
            {
                bottomSpace = safeAreaInsets.top;
            }
                break;
            default:
            {
                bottomSpace = safeAreaInsets.bottom;
            }
                break;
        }
    }
    return bottomSpace;
}

@end

注:開放介面可用範圍在iOS 11以上。