SwiftUI自定義UITabBar如果不使用系統(tǒng)的TabbarView的話在辆,自定義樣式是很方便的,但是出現(xiàn)一個問題就是無法使root頁面保持只初始化一次峭判。
例如:有兩個TabBar,Tabbar1中有一個listView,當(dāng)滑動到50行的時候,在切換到TabBar2后,再次返回TabBar1棕叫,此時上一次滑動到的50行就會被重置林螃,ListView的狀態(tài)將會被重置。
下面分享一下實現(xiàn)自定義方式的其中一種【使用系統(tǒng)TabBarView俺泣,但是使用自定義View遮蓋住系統(tǒng)的TabBar,只使用系統(tǒng)TabBar的切換功能】
直接上代碼
struct CMTabbarView: View {
@State var selectedTab = Tab.home
enum Tab: Int {
case home, photo, media, file
}
func tabbarItem(text: String, image: String,tab:Tab,seletedImage:String) -> some View {
VStack(spacing:0) {
Image(selectedTab == tab ? seletedImage : image)
.imageScale(.large)
Text(text)
.font(Font.system(size: 12))
.fontWeight(.medium)
.foregroundColor(selectedTab == tab ? Color.tabbar_selected_color : Color.tabbar_normal_color)
.lineLimit(1)
.padding(.top, 3)
}.frame(width: UIScreen.main.bounds.size.width / 5.0, height: 49, alignment: .center).background(Color.white)
}
var body: some View {
ZStack(alignment: .bottom){
///還是使用系統(tǒng)的TabView 但是使用ZStack替換成自己將要自定義的樣式
TabView(selection: $selectedTab) {
Phtots(text: "Screen", color: Color(.systemRed)).tag(Tab.home)
Media(text: "Screen", color: Color(.systemRed)).tag(Tab.photo)
Phtots(text: "Screen", color: Color(.systemRed)).tag(Tab.media)
File(text: "Screen", color: Color(.systemRed)).tag(Tab.file)
}.background(Color.red)
HStack(alignment:.center,spacing: 0){
self.tabbarItem(
text: "首頁",
image: "icon_shouye",
tab: Tab.home,
seletedImage: "icon_shouye_sel"
)
.background(Color.blue).onTapGesture {
selectedTab = .home
}
self.tabbarItem(
text: "照片",
image: "icon_zhaopian",
tab: Tab.photo,
seletedImage: "icon_zhaopian_sel"
)
.background(Color.red)
.onTapGesture {
selectedTab = .photo
}
Image("button_daoru").imageScale(.small)
.frame(
width: UIScreen.main.bounds.size.width / 5.0,
height: 49,
alignment: .center
)
.background(Color.white)
.onTapGesture {
print("add action")
}
self.tabbarItem(
text: "視頻",
image: "icon_shiping",
tab: Tab.media,
seletedImage: "icon_shiping_sel"
)
.onTapGesture {
selectedTab = .media
}
self.tabbarItem(
text: "文件",
image: "icon_wenjian",
tab: Tab.file,
seletedImage: "icon_wenjian_sel"
)
.onTapGesture {
selectedTab = .file
}
}
.frame(
width: UIScreen.main.bounds.size.width,
height: 49,
alignment: .center
)
}
}
}