自定义微信小程序导航(兼容各种手机)

 

详细代码请见github,请点击地址,其中有原生小程序的实现,也有wepy版本的实现

了解小程序默认导航

如上图所示,微信导航分为两部分,第一个部分为statusBarHeight,刘海屏手机(iPhone X,小米8等)会比其他的手机高很多,第二部分为titleBarHeight,安卓和IOS的高度不同,但是IOS高度是一样的,IOS高度是一样的,

所以我们要实现一个兼容不同手机的导航必须要根据不同的手机实现statusBarHeight和titleBarHeight

第一步:全局设置

把app.json中的window中的navigationStyle设置为custom官方文档链接

设置完之后发现导航栏变成了如下图所示,只剩下了右上角胶囊按钮

第二步:确定导航栏两部分的高度

(1)确定第一部分statusBarHeight的高度,这部分是手机用来展示时间,信号和手机电量的,我们可以从wx.getSystemInfo从获得

复制代码
wx.getSystemInfo({   success: function(res) {     console.log(res.statusBarHeight)   } })
复制代码

(2)第二部分titleBarHeight为小程序导航栏的高度,经过我查询无数文档和实践得知,在iPhone上titleBarHeight=44px,在安卓上titleBarHeight = 48px

(3)最后总结一下微信小程序的高度代码为

复制代码
wx.getSystemInfo({   success: function(res) {     let titleBarHeight = 0     if (res.model.indexOf('iPhone') !== -1) {       titleBarHeight = 44     } else {       titleBarHeight = 48     }     that.setData({       statusBarHeight: res.statusBarHeight,       titleBarHeight: titleBarHeight     });   },   failure() {     that.setData({       statusBarHeight: 0,       titleBarHeight: 0     });   } })
复制代码

第三步:编写Navigation组件

(1)Navigation.js

复制代码
const app = getApp(); Component({   properties: {     //小程序页面的标题     title: {       type: String,       default: '默认标题'     },     //是否展示返回和主页按钮     showIcon: {       type: Boolean,       default: true     }   },    data: {     statusBarHeight: 0,     titleBarHeight: 0,   },    ready: function () {     // 因为每个页面都需要用到这连个字段,所以放到全局对象中     if (app.globalData && app.globalData.statusBarHeight && app.globalData.titleBarHeight) {       this.setData({         statusBarHeight: app.globalData.statusBarHeight,         titleBarHeight: app.globalData.titleBarHeight       });     } else {       let that = this       wx.getSystemInfo({         success: function(res) {           if (!app.globalData) {             app.globalData = {}           }           if (res.model.indexOf('iPhone') !== -1) {             app.globalData.titleBarHeight = 44           } else {             app.globalData.titleBarHeight = 48           }           app.globalData.statusBarHeight = res.statusBarHeight           that.setData({             statusBarHeight: app.globalData.statusBarHeight,             titleBarHeight: app.globalData.titleBarHeight           });         },         failure() {           that.setData({             statusBarHeight: 0,             titleBarHeight: 0           });         }       })     }   },    methods: {     headerBack() {       wx.navigateBack({         delta: 1,         fail(e) {           wx.switchTab({             url: '/pages/main/main'           })         }       })     },     headerHome() {       wx.switchTab({         url: '/pages/main/main'       })     }   } })
关键字:
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信