IphoneX系列帶有劉海屏,在游戲開發過程中,會出現部分重要UI會被遮擋的問題。為了解決這個問題,我采取的做法是將會被劉海屏遮擋的UI移到安全的區域。而如果只是單純的移動,如果屏幕旋轉的話,在另外一側就會留出空白了(如下圖)。這樣就會顯得很丑,理想中的是我左右旋轉,UI根據是否靠著劉海屏進行位置調整。
左右旋轉后劉海屏留出多余的空白.png
1.在oc代碼中添加監聽
//添加屏幕監聽
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onDeviceOrientationDidChange)
name:UIDeviceOrientationDidChangeNotification object:nil];
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
添加回調方法,因為我的游戲只需要添加左右旋轉的適應,所以只在橫屏切換的時候發送消息,SDKTools.UnitySendMessage是封裝的一個oc調用游戲里預制件上的c#方法,這邊就不細說了。
- (void)onDeviceOrientationDidChange{
//獲取當前設備Device
UIDevice *device = [UIDevice currentDevice] ;
//識別當前設備的旋轉方向
switch (device.orientation) {
case UIDeviceOrientationFaceUp:
NSLog(@"屏幕幕朝上平躺");
break;
case UIDeviceOrientationFaceDown:
NSLog(@"屏幕朝下平躺");
break;
case UIDeviceOrientationUnknown:
//系統當前無法識別設備朝向,可能是傾斜
NSLog(@"未知方向");
break;
case UIDeviceOrientationLandscapeLeft:
NSLog(@"屏幕向左橫置");
[SDKTools UnitySendMessage:@"screenDirChange" result:YES json:@"{\"screenDir\":1}"];
break;
case UIDeviceOrientationLandscapeRight:
NSLog(@"屏幕向右橫置");
[SDKTools UnitySendMessage:@"screenDirChange" result:YES json:@"{\"screenDir\":2}"];
break;
case UIDeviceOrientationPortrait:
NSLog(@"屏幕直立");
break;
case UIDeviceOrientationPortraitUpsideDown:
NSLog(@"屏幕直立,上下顛倒");
break;
default:
NSLog(@"無法識別");
break;
}
銷毀注冊:
- (void) removeDeviceRotateObserver {
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIDeviceOrientationDidChangeNotification
object:nil];
[[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
}
- (void)dealloc {
[self removeDeviceRotateObserver];
}
2.接收到消息后,判斷是否是劉海屏,如果是,修改UI位置就可以了。
//是否有劉海屏
+ (BOOL)isIPhoneX {
BOOL iPhoneX = NO;
if (UIDevice.currentDevice.userInterfaceIdiom != UIUserInterfaceIdiomPhone) {//判斷是否是手機
return iPhoneX;
}
if (@available(iOS 11.0, *)) {
UIWindow *mainWindow = [[[UIApplication sharedApplication] delegate] window];
if (mainWindow.safeAreaInsets.bottom > 0.0) {
iPhoneX = YES;
}
}
return iPhoneX;
}
extern "C" {
bool SDK_GetIsIphoneX()
{
BOOL result = [SDKTools isIPhoneX];
return result == YES;
}
}