在使用uni-app开发app应用时候,应用需要横屏显示,那么该如何实现呢?
一、打开APP就是横屏
方式一:
打开pages.json页面,在globalStyle中添加pageOrientation选项,如下:
"globalStyle": {
"navigationStyle":"custom",
"pageOrientation": "landscape" //横屏配置,支持auto/portrait/landscape
}
属性说明:
“auto”:如果页面添加了上述声明,则在屏幕旋转时,这个页面将随之旋转,显示区域尺寸也会随着屏幕旋转而变化;
“portrait”:表示固定为竖屏显示。
“landscape”:表示固定为横屏显示。
Ps:横屏配置,全局屏幕旋转设置(仅 APP/微信/QQ小程序)。
注意要关闭手机的方向锁定
方式二:
onLaunch: function() {
// #ifdef APP-PLUS
plus.screen.unlockOrientation();//设置横屏-全局globalStyle-pageOrientation已设置
plus.screen.lockOrientation('landscape-primary');
// #endif
},
说明:锁定屏幕方向后屏幕只能按锁定的屏幕方向显示,关闭当前页面后仍然有效。 可再次调用此方法修改屏幕锁定方向或调用unlockOrientation()方法恢复到应用的默认值。
lockOrientation参数值。锁定屏幕方向可取以下值:
“portrait-primary”: 竖屏正方向;
“portrait-secondary”: 竖屏反方向,屏幕正方向按顺时针旋转180°;
“landscape-primary”: 横屏正方向,屏幕正方向按顺时针旋转90°;
“landscape-secondary”: 横屏方向,屏幕正方向按顺时针旋转270°;
“portrait”: 竖屏正方向或反方向,根据设备重力感应器自动调整;
“landscape”: 横屏正方向或反方向,根据设备重力感应器自动调整;
二、设置APP内某个页面为横屏
需要在对应页面onShow()的方法中添加plus.screen.lockOrientation方法:
onShow() {
// #ifdef APP-PLUS
plus.screen.unlockOrientation();//解除屏幕方向的锁定,但是不一定是竖屏;
plus.screen.lockOrientation('landscape-primary');
// #endif
},
在页面卸载时候,需要注意还原哦,比如:
/页面卸载时切换为竖屏配置
onUnload() {
// #ifdef APP-PLUS
plus.screen.lockOrientation('portrait-primary'); //锁死屏幕方向为竖屏
// #endifs
}
三、横屏 IOS安全区如何设置全屏
在应用需要全屏显示的时候,我们发现在ios中,安全区域是可能存在空白的,比如全屏web-view的组件,实现方法如下:
setStyle(){//设置样式
let style={}
if(!this.screen){//竖屏
let safeTopArea = uni.getSystemInfoSync().safeAreaInsets.top
let safeBoottom = uni.getSystemInfoSync().safeAreaInsets.bottom
style={
top: - safeTopArea, //ios的位置上移顶部安全区域的高度
height:uni.getSystemInfoSync().windowHeight + safeBoottom + safeTopArea, //高度+安全区域的高度
}
if(!this.safeTop){//不处理顶部安全区
style={
top:0,
height:uni.getSystemInfoSync().windowHeight + safeBoottom,
}
}
}else{//横屏
let safeLeftArea = uni.getSystemInfoSync().safeAreaInsets.left
let safeRightArea = uni.getSystemInfoSync().safeAreaInsets.left
style={
left: - safeRightArea,
width: uni.getSystemInfoSync().windowWidth + safeLeftArea + safeRightArea,
height:'100%',
}
}
let currentWebview = this.$scope.$getAppWebview() //获取webview
let wv = currentWebview.children()[0]
wv.setStyle(style)
},
该方法仅供参考。
四、uniapp ios无法横竖屏
使用上面的代码,在ios中如果横竖屏切换,会出现无法生效的问题,我们需要在manifest.json文件和pages.json文件进行如下配置
//第一在manifest.json文件下的app-plus=>distribute下配置:
"screenOrientation" : [
"portrait-primary",
"landscape-primary",
"portrait-secondary",
"landscape-secondary"
],
//第二在pages.json文件的globalStyle下配置:
"pageOrientation": "auto"
//最后在需要横竖屏的页面调用
//竖屏
plus.screen.lockOrientation('portrait-primary');
//横屏
plus.screen.lockOrientation('landscape-primary');