实现过程
1.隐藏掉默认导航栏,app.json
中的window
配置
1 2 3 4 5
| "window":{ ... "navigationStyle": "custom" }
|
2.自定义导航栏组件
导航栏构成主要有顶部的手机状态栏statusBar
和标题栏titleBar
构成
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| //占位 <view class='place-holder' style="height: {{statusBarHeight+titleBarHeight}}px;"></view>
//导航栏主体 <view class="custom-class nav-bar"> //手机顶部状态栏 <view class='tool-bar' style='height: {{statusBarHeight}}px'></view> //标题栏 <view class='title-bar' style="height: {{titleBarHeight}}px;"> //左侧功能区域 <view class='left-cell' style="line-height:{{titleBarHeight}}px"> <view wx:if="{{isShowBakcBtn}}">返回</view> <view wx:if="{{isShowHomeBtn}}">首页</view> </view> //标题区域 <view class='center-cell' style="line-height:{{titleBarHeight}}px"> {{title}} </view> </view> </view>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| properties: { title: { type: String, value: '' }, isShowBakcBtn: { //是否显示返回按钮 type: Boolean value: true, }, isShowHomeBtn: { //是否显示主页按钮 type: Boolean, value: true, } }, data: { statusBarHeight: 20, //状态栏高度 titleBarHeight: 0, //标题栏高度 },
|
由于分享的页面打开后,拿不到页面的路由栈,此种情况主要是为了适配某个详情页面分享后,打开的页面不显示返回按钮使用
1 2 3 4 5 6 7 8 9 10 11 12
| attached(){ let pages = getCurrentPages();
let isShowBakcBtn = true;
if (pages.length === 1) { isShowBakcBtn = false } ... }
|
计算statusBar
和titleBar
高度
1 2 3 4 5 6 7 8 9 10
| attached(){ ... const res = wx.getSystemInfoSync(); const statusBarHeight = res.statusBarHeight;
const custom = wx.getMenuButtonBoundingClientRect(); titleBarHeight = Math.floor(custom.bottom + custom.top - (statusBarHeight * 2)); ... }
|
注意,因为getMenuButtonBoundingClientRect
方法之前有BUG,在iOS设备上拿不到数据,所以这里之前采用了固定写法来设置标题栏高度,目前BUG已经修复,使用上面直接获取的方法暂未发现BUG
1 2 3 4 5 6 7 8 9 10 11 12
| if (res.system.search('Android') !== -1) { titleBarHeight = Math.floor(custom.bottom + custom.top - (statusBarHeight * 2)); } else if (res.system.search('iOS') !== -1) { if (res.model.search('iPhone X') !== -1) { titleBarHeight = TOTALBAR_HEIGHT.iPhoneX - statusBarHeight } else { titleBarHeight = TOTALBAR_HEIGHT.iPhone - statusBarHeight } }
|
1 2 3 4
| const TOTALBAR_HEIGHT = { 'iPhone': 64, 'iPhoneX': 88, }
|
注意:web-view页面自定义导航栏不会生效