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;
}
}
网友评论