在微信小程序开发中,自定义`tabBar`是提升用户界面体验的重要环节。原生的微信小程序`tabBar`虽然提供了基本的样式和功能,但往往无法满足开发者对个性化设计的需求。本文将深入探讨如何实现一个中间圆形凸起的自定义`tabBar`,并介绍如何使其支持`darkMode`(深色主题)以及iPhoneX系列底部横线的自适应。
我们需要了解微信小程序中的`app.json`配置文件。这是全局配置应用的地方,包括页面路径、窗口表现、网络超时时间等。要自定义`tabBar`,我们需要在`app.json`中添加相应的配置:
```json
{
"tabBar": {
"custom": true,
"color": "#7A7E83",
"selectedColor": "#3cc51f",
"borderStyle": "black",
"list": [
{
"pagePath": "pages/index/index",
"text": "首页",
"iconPath": "image/icon_index.png",
"selectedIconPath": "image/icon_index_selected.png"
},
{
"pagePath": "pages/logs/logs",
"text": "日志",
"iconPath": "image/icon_logs.png",
"selectedIconPath": "image/icon_logs_selected.png"
}
]
}
}
```
设置`custom`为`true`表示我们要使用自定义的`tabBar`,而不是默认的样式。
接下来,我们需要创建一个`custom-tab-bar`目录,包含`index.wxml`、`index.wxss`、`index.js`和`index.json`四个文件。这里我们主要关注`index.wxml`和`index.wxss`,这两个文件用于定义`tabBar`的结构和样式。
在`index.wxml`中,我们可以创建一个圆形的`view`作为中间凸起的部分,并为每个按钮添加点击事件:
```html
<view class="container">
<view wx:for="{{tabs}}" wx:key="index" bindtap="switchTab" data-index="{{index}}">
<view class="tab {{currentTab === index ? 'active' : ''}}">
<view class="circle" wx:if="{{index === 1}}"></view>
<image src="{{item.iconPath}}" class="icon {{currentTab === index ? 'selected' : ''}}"/>
<text>{{item.text}}</text>
</view>
</view>
</view>
```
在`index.wxss`中,我们需要编写CSS样式来实现圆形凸起效果和深色模式的适配:
```css
.container {
display: flex;
justify-content: center;
align-items: center;
height: 88rpx;
background-color: #fff;
}
.circle {
width: 60rpx;
height: 60rpx;
border-radius: 50%;
background-color: #3cc51f;
position: absolute;
left: 50%;
top: 20rpx;
transform: translateX(-50%);
}
.tab {
flex: 1;
position: relative;
display: flex;
align-items: center;
justify-content: center;
height: 100%;
font-size: 28rpx;
color: #7A7E83;
transition: color .3s;
}
.tab.active {
color: #3cc51f;
}
.selected {
transform: rotate(180deg);
}
```
在`index.js`中,我们需要处理页面切换的逻辑,记录当前选中的`tab`并触发相应的事件:
```javascript
Page({
data: {
currentTab: 0,
tabs: [
// ...
],
},
switchTab(e) {
const index = e.currentTarget.dataset.index;
this.setData({
currentTab: index,
});
wx.switchTab({
url: `/pages/logs/logs`,
});
},
});
```
至于`darkMode`的支持,微信小程序提供了`wx.getSystemInfoSync().darkMode`接口来判断当前是否启用深色模式。在`index.wxss`中,我们可以使用媒体查询来实现深色主题下的样式调整:
```css
@media (prefers-color-scheme: dark) {
.container {
background-color: #111;
}
.tab {
color: #ccc;
}
.tab.active {
color: #3cc51f;
}
}
```
关于iPhoneX系列底部横线的自适应,微信小程序已经自动处理了大部分适配问题。如果遇到特殊情况,可以在`app.wxss`中添加以下代码:
```css
page {
padding-bottom: env(safe-area-inset-bottom);
}
```
这段代码会根据设备的安全区域进行底部边距的调整,确保内容不会被刘海屏或Home Indicator遮挡。
通过自定义`tabBar`组件,我们可以实现微信小程序中中间圆形凸起的效果,同时支持深色模式和iPhoneX系列底部横线的自适应。这不仅提升了用户体验,也为我们的小程序赋予了更多个性化的元素。
评论0
最新资源