iOS 部分界面强制屏幕横屏

不赘述直接切入本次话题部分界面屏幕横屏

因为是部分界面屏幕横屏故我们先设置项目只能竖屏,如下:
AppDelegate.h文件中带么设置 如下:

//.h文件夹添加属性
@property (nonatomic,assign)BOOL isCanRotation;//是否可旋转
//.m文件中
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    if (_ isCanRotation){//默认是NO故不可旋转
//这里设置屏幕旋转的方向
        return  UIInterfaceOrientationMaskLandscapeRight;
    } else {
        return UIInterfaceOrientationMaskPortrait;
    }
}

其实选中工程 ->General->Deployment info ->Device Orientation 只要勾选Portrait也可禁止横屏。
但是要求部分界面横屏所以不能固定死。

在需要横屏的界面 或者点击事件下添加图下代码即可:

//设置横屏
    NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
    [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];

//设置竖屏
    NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
    [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];

这样就很简单的完成部分界面横屏的强制转换了。

话题未完!!!

有的小伙伴可能会遇到以下一个问题:

问题描述

有A、B俩个界面,从A界面到B界面要求B界面立即横屏,返回的时候A界面是竖屏的。
在B界面的时候,如果你在点击返回事件前手机是竖屏的,那么你会发现当你点击返回的时候屏幕并没有真正的竖屏。

原因分析

因为手机物理竖屏的时候系统获取的当前状态就是竖屏了,所以当你点击返回A界面竖屏的时候屏幕并没有真正的竖屏。

解决方法

只要干扰手机获取当前的物理状态就好了。

    NSNumber *orientationUnknown = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
    [[UIDevice currentDevice] setValue:orientationUnknown forKey:@"orientation"];

在设置屏幕状态前加上Unknown 状态即可

iOS 16 时候你会发现横屏代码失效解决如下

       if #available(iOS 16.0 , *){
            //在视图控制器中,获取窗口场景。
            guard let windowScene = view.window?.windowScene else { return }
            //windowScene.requestGeometryUpdate(.iOS(interfaceOrientations: .landscapeRight))
            //(同上) 请求窗口场景旋转到任何景观方向。
            windowScene.requestGeometryUpdate(.iOS(interfaceOrientations:   .landscapeRight)) { error in
              print("---requestGeometryUpdate 处理拒绝请求 \n\n")
            }
          //处理横屏View布局...
        }else{
            let orientationTarget = NSNumber(value: UIInterfaceOrientation.landscapeRight.rawValue)
            UIDevice.current.setValue(orientationTarget, forKey: "orientation")
            UIViewController.attemptRotationToDeviceOrientation()
        }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。