feat: 优化底部导航栏组件及初始化逻辑
- 在CommonComponents中为BottomTabBar添加了便捷初始化和最简初始化方法,简化了外部使用。 - 新增内部默认items方法,确保底部导航栏的图标资源一致性。 - 在MainPage中更新BottomTabBar的使用方式,直接传入viewModel,提升代码可读性和维护性。
This commit is contained in:
@@ -25,6 +25,36 @@ struct BottomTabBar: View {
|
||||
var contentPadding: EdgeInsets = EdgeInsets(top: 12, leading: 0, bottom: 12, trailing: 0)
|
||||
var horizontalPadding: CGFloat = 0
|
||||
|
||||
// 便捷初始化:内部固定 tabs,避免外部重复声明
|
||||
init(
|
||||
selectedId: Binding<String>,
|
||||
onSelect: @escaping (String) -> Void,
|
||||
contentPadding: EdgeInsets = EdgeInsets(top: 12, leading: 0, bottom: 12, trailing: 0),
|
||||
horizontalPadding: CGFloat = 0
|
||||
) {
|
||||
self.items = BottomTabBar.defaultItems()
|
||||
self._selectedId = selectedId
|
||||
self.onSelect = onSelect
|
||||
self.contentPadding = contentPadding
|
||||
self.horizontalPadding = horizontalPadding
|
||||
}
|
||||
|
||||
// 最简初始化:直接接受 viewModel,内部处理所有逻辑
|
||||
init(viewModel: MainViewModel) {
|
||||
self.items = BottomTabBar.defaultItems()
|
||||
self._selectedId = Binding(
|
||||
get: { viewModel.selectedTab.rawValue },
|
||||
set: { raw in
|
||||
if let tab = MainViewModel.Tab(rawValue: raw) {
|
||||
viewModel.onTabChanged(tab)
|
||||
}
|
||||
}
|
||||
)
|
||||
self.onSelect = { _ in } // 保留但不再使用
|
||||
self.contentPadding = EdgeInsets(top: 12, leading: 0, bottom: 12, trailing: 0)
|
||||
self.horizontalPadding = 0
|
||||
}
|
||||
|
||||
// 使用 BottomTabView.swift 中的图片资源名进行映射
|
||||
private func assetIconName(for item: TabBarItem, isSelected: Bool) -> String? {
|
||||
switch item.id {
|
||||
@@ -37,6 +67,14 @@ struct BottomTabBar: View {
|
||||
}
|
||||
}
|
||||
|
||||
// 内部默认 items(与资源映射保持一致)
|
||||
private static func defaultItems() -> [TabBarItem] {
|
||||
return [
|
||||
TabBarItem(id: "feed", title: "Feed", systemIconName: "list.bullet"),
|
||||
TabBarItem(id: "me", title: "Me", systemIconName: "person.circle")
|
||||
]
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 8) {
|
||||
ForEach(items) { item in
|
||||
|
@@ -27,24 +27,10 @@ struct MainPage: View {
|
||||
VStack {
|
||||
Spacer()
|
||||
// 底部导航栏(组件化)
|
||||
BottomTabBar(
|
||||
items: [
|
||||
TabBarItem(id: MainViewModel.Tab.feed.rawValue, title: MainViewModel.Tab.feed.title, systemIconName: MainViewModel.Tab.feed.iconName),
|
||||
TabBarItem(id: MainViewModel.Tab.me.rawValue, title: MainViewModel.Tab.me.title, systemIconName: MainViewModel.Tab.me.iconName)
|
||||
],
|
||||
selectedId: Binding(
|
||||
get: { viewModel.selectedTab.rawValue },
|
||||
set: { raw in
|
||||
if let tab = MainViewModel.Tab(rawValue: raw) {
|
||||
viewModel.onTabChanged(tab)
|
||||
}
|
||||
}
|
||||
),
|
||||
onSelect: { _ in }
|
||||
)
|
||||
BottomTabBar(viewModel: viewModel)
|
||||
.frame(height: 80)
|
||||
.padding(.horizontal, 24)
|
||||
.padding(.bottom, 100)
|
||||
.padding(.bottom)
|
||||
}
|
||||
}.ignoresSafeArea(.all)
|
||||
}
|
||||
|
Reference in New Issue
Block a user