uniapp支持App横竖屏开发总结

一、需求:

app要支持重力感应自动切换横竖屏,并切换后样式不能错乱

二、实现

官方文档
官方Git
manifest.json文件中

"app-plus" : {
	"screenOrientation" : [
		 "portrait-primary",
		 "portrait-secondary",
		 "landscape-primary",
		 "landscape-secondary"
	],
}

pages.json文件中

"globalStyle": {
		"pageOrientation": "auto"
	},
"app-plus": {
	"screenOrientation": [
		"portrait-primary",     //可选,字符串类型,支持竖屏
		"portrait-secondary",   //可选,字符串类型,支持反向竖屏
		"landscape-primary",    //可选,字符串类型,支持横屏
		"landscape-secondary"   //可选,字符串类型,支持反向横屏
	]
},

三、额外补充

3.1 合理性

我感觉这东西官方uniapp应该默认配置里就有,而不应该让程序员再手动添加,因为自动旋转大部分APP都支持,不需要的人手动置为false比较合理

3.2 旋转后的样式问题

旋转后可能出现样式问题或者白屏,导致问题点原因有很多,有一大部分原因是uniapp对涉及安卓原生交互的东西处理的其实并不太好,我这里只列一下我了解到的
①不要使用rpx,使用px,因为rpx是根据屏幕尺寸来计算的,回到首页时候,页面获取到的屏幕尺寸还是横屏的尺寸;如果非要使用rpx,要加定时器实时监控页面尺寸
②不要使用uni.navigateBack()返回,监听页面返回使用uni.redirectTo跳转或uni.switchTab,如果直接跳回想要跳转的页面还是出现样式问题,可以尝试先跳转一个空白页面,在空白页面跳转至想要跳回的页面就好了

3.2 如果你要强制APP所有页面都是横屏:

pages.json

"globalStyle": {
	"pageOrientation": "landscape",
}

manifest.json

"distribute" : {
	"orientation" : [ "portrait-primary" ]
},

3.3 如何在页面里手动旋转页面(单独让某个页面支持旋转)

export default {
  mounted() {
    // 监听屏幕方向变化
    window.addEventListener('orientationchange', this.handleOrientationChange)
  },
  destroyed() {
    // 移除屏幕方向变化的监听
    window.removeEventListener('orientationchange', this.handleOrientationChange)
  },
  methods: {
    handleOrientationChange() {
      // 横屏
      if (window.orientation === 90 || window.orientation === -90) {
        this.lockOrientation('landscape')
      }
      // 竖屏
      else {
        this.lockOrientation('portrait')
      }
    },
    lockOrientation(orientation) {
      if (typeof plus !== 'undefined' && typeof plus.screen !== 'undefined') {
        plus.screen.lockOrientation(orientation)
      }
    }
  }
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值