uni-app App端锁定横屏需四步:一、manifest.json的app-plus.distribute中iOS配orientation数组["landscape-primary","landscape-secondary"],Android配"landscape";二、在onShow中调用uni.setScreenOrientation({orientation:'landscape'})并检查返回值;三、重新云打包或制作自定义基座;四、WebView需监听resize或orientation变化适配尺寸。

uni-app App端怎么锁定横屏(iOS/Android)
uni-app 默认不支持直接锁屏,必须通过原生层干预。H5 和小程序端的 screen.orientation.lock 在 App 端根本无效,强行调用会静默失败或报错 NotSupportedError。
真正起作用的是 DCloud 提供的 setScreenOrientation API,但它只在 App 端生效,且仅对当前页面有效 —— 页面卸载后自动恢复系统默认方向。
- 只在
onLoad或onShow中调用,onReady太晚,部分 Android 机型已错过窗口初始化时机 - 必须配合
manifest.json预设,否则 iOS 会直接拒绝锁定(白屏或闪退) - Android 侧需注意 targetSdkVersion 影响:Android 12+ 要求 Activity 显式声明
android:screenOrientation,uni-app 的基座已处理,但自定义原生插件可能破坏它
manifest.json 里必须配哪几项
没配 manifest.json,setScreenOrientation 在 iOS 上必失败,Android 也可能降级为“仅建议方向”而非强制锁定。
关键配置在 mp-weixin 同级的 app-plus 节点下:
"app-plus": {
"usingComponents": true,
"nvueStyleCompiler": "uni-app",
"splashscreen": {
"alwaysShowBeforeRender": true,
"waiting": true
},
"distribute": {
"ios": {
"orientation": ["landscape-primary", "landscape-secondary"]
},
"android": {
"orientation": "landscape"
}
}
}
-
ios.orientation必须是数组,且只能填"landscape-primary"和/或"landscape-secondary";填"landscape"会忽略 -
android.orientation填字符串"landscape"即可,不区分主次方向(由系统自动适配) - 改完必须重新制作自定义基座或云打包,真机调试时用“运行到手机或模拟器”不会生效
setScreenOrientation 调用时机和兼容性坑
API 是异步的,返回 Promise,但失败时不会抛异常,而是 resolve 一个 { result: 'fail', errMsg: 'xxx' } 对象 —— 很多开发者没检查返回值,以为锁定了,实际没反应。
- 务必在
onShow里调用,因为用户从后台切回时方向可能已变;onLoad只触发一次,无法应对切后台再回来的场景 - iOS 真机上首次调用可能因权限延迟失败,建议加 100ms 延迟重试(最多 1 次),避免卡死
- 部分 Android 定制 ROM(如华为 EMUI、小米 MIUI)会拦截横屏请求,此时
result为'fail',errMsg含'permission denied'或'operation not allowed' - 示例写法:
onShow() { uni.setScreenOrientation({ orientation: 'landscape' }).then(res => { if (res.result !== 'ok') { console.warn('横屏锁定失败:', res.errMsg) } }) }
横屏下 WebView 内容拉伸/错位怎么办
强制横屏后, 或内嵌 H5 页面常出现宽度超限、滚动条异常、CSS 媒体查询失效等问题 —— 根本原因是 WebView 容器尺寸没随屏幕旋转实时更新,或 H5 自身未监听 resize。
- App 端 WebView 不会自动响应
setScreenOrientation,需手动触发uni.getSystemInfo获取新窗口尺寸,再通知 H5 调整布局 - H5 页面必须监听
window.orientation变化(iOS)或resize(Android),不能只靠 CSS@media (orientation: landscape) - uni-app 的
nvue页面不受影响,但vue页面中使用flex布局时,若父容器未设width: 100%,横屏后内容仍按竖屏宽度渲染
强制横屏不是加个 API 就完事,manifest.json 配置、调用时机、失败兜底、WebView 协同这四块缺一不可。最容易被跳过的其实是 iOS 的 distribute.ios.orientation 数组写法和 Android 云打包后的验证 —— 本地调试成功不等于真机可用。










