如何在SwiftUI中创建共享导航栏实现多视图间相互跳转
底部共享标签导航栏实现方案
底部跨页面共享的导航栏通常称为标签栏(Tab Bar),可以按照以下方案实现A、B、C三个页面的跳转功能:
核心思路
- 所有三个页面复用完全相同的底部标签栏代码
- 自动识别当前页面,给对应标签按钮添加高亮选中样式
- 点击其他标签按钮直接跳转至对应页面即可
原生HTML/CSS/JS实现代码
HTML结构(每个页面底部都加入这段代码)
<!-- 底部标签导航栏 --> <div class="bottom-tab-bar"> <div class="tab-item" data-page="a.html"> <img src="https://i.sstatic.net/mahzgm.png" alt="页面A"> <span>页面A</span> </div> <div class="tab-item" data-page="b.html"> <img src="https://i.sstatic.net/i4n8mm.png" alt="页面B"> <span>页面B</span> </div> <div class="tab-item" data-page="c.html"> <img src="https://i.sstatic.net/uSsCym.png" alt="页面C"> <span>页面C</span> </div> </div> <!-- 页面主体内容记得加bottom-padding避免被导航栏遮挡 --> <div class="page-content"> <!-- 页面自身内容写在这里 --> </div>
CSS样式(写入公共样式文件)
/* 底部导航栏固定定位 */ .bottom-tab-bar { position: fixed; bottom: 0; left: 0; width: 100%; height: 55px; display: flex; justify-content: space-around; align-items: center; background-color: #ffffff; border-top: 1px solid #e5e5e5; z-index: 999; } /* 单个标签项样式 */ .tab-item { display: flex; flex-direction: column; align-items: center; font-size: 12px; color: #666666; cursor: pointer; } /* 选中状态样式 */ .tab-item.active { color: #2385bb; } .tab-item img { width: 24px; height: 24px; margin-bottom: 3px; } /* 页面内容预留底部边距 */ .page-content { padding-bottom: 70px; }
交互逻辑(写入公共JS文件)
// 页面加载后初始化标签栏状态 document.addEventListener('DOMContentLoaded', () => { // 获取当前页面文件名 const currentPage = window.location.pathname.split('/').pop() || 'a.html' const tabItems = document.querySelectorAll('.tab-item') tabItems.forEach(item => { // 给当前页面对应标签加高亮 if (item.dataset.page === currentPage) { item.classList.add('active') } // 绑定点击跳转事件 item.addEventListener('click', () => { window.location.href = item.dataset.page }) }) })
单页应用场景优化
如果你用Vue、React等框架开发单页应用,可以直接把标签栏封装为公共全局组件,配合前端路由实现跳转,不需要每个页面重复引入代码:
- Vue项目可配合
vue-router,用<router-link>封装标签项,自动匹配当前路由激活状态 - React项目可配合
react-router-dom,用useNavigate实现跳转、useLocation获取当前路由判断激活状态
内容的提问来源于stack exchange,提问作者cbusch
相关产品推荐
相关产品推荐

