SwiftUI自定义UITabBar如果不使用系统的TabbarView的话,自定义样式是很方便的,但是出现一个问题就是无法使root页面保持只初始化一次。
例如:有两个TabBar,Tabbar1中有一个listView,当滑动到50行的时候,在切换到TabBar2后,再次返回TabBar1,此时上一次滑动到的50行就会被重置,ListView的状态将会被重置。
Simulator Screen Shot - iPhone 8 - 2022-02-17 at 21.01.28.png
下面分享一下实现自定义方式的其中一种【使用系统TabBarView,但是使用自定义View遮盖住系统的TabBar,只使用系统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){
///还是使用系统的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
)
}
}
}
网友评论