You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iPad应用启动时获取屏幕方向(左/右/上/下)的方法

在iPad上无需旋转设备区分LandscapeLeft与LandscapeRight(允许私有API)

官方API优先方案

你当前的代码仅判断了是否为横屏,但UIWindowScene.interfaceOrientation本身包含具体方向枚举,启动时直接读取即可区分LandscapeLeft和LandscapeRight,无需旋转设备:

guard let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene else {
    print("无法获取窗口场景")
    return
}

let interfaceOrientation = scene.interfaceOrientation
switch interfaceOrientation {
case .landscapeLeft:
    print("当前为Landscape Left方向")
case .landscapeRight:
    print("当前为Landscape Right方向")
case .portrait, .portraitUpsideDown:
    print("当前为竖屏方向")
default:
    print("方向未知")
}

如果启动时该值能返回准确结果,这是最稳妥的方案,无需依赖私有API。

私有API fallback方案

若官方API在你的场景下仍无法返回具体横屏方向,可使用UIDevice的私有属性获取原始方向(注意:私有API可能随iOS版本变更,仅适合非上架应用):

// 读取UIDevice私有属性_rawOrientation获取原始方向值
if let rawOrientation = UIDevice.current.value(forKey: "_rawOrientation") as? Int {
    switch rawOrientation {
    case 1:
        print("Portrait")
    case 2:
        print("Portrait Upside Down")
    case 3:
        print("Landscape Right")
    case 4:
        print("Landscape Left")
    default:
        print("方向未知")
    }
}

上述Int值对应关系基于iOS 16-17版本,不同iOS版本可能存在差异,使用前需在目标系统版本上验证。

内容的提问来源于stack exchange,提问作者brainray

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 16:02:45