因为要兼容Ios13把,Lable的用法不适用,所以还是回归原始方式实现tabbarItem。
image.png搜索了两种自定义的实现方式
方法一、根据选中项绑定显示的图片
import SwiftUI
struct ContentView: View {
enum Tab: Int {
case home, mall, my
}
@State var selectedTab = Tab.home
var body: some View {
NavigationView {
TabView(selection: $selectedTab) {
HomeView().tag(Tab.home) .tabItem {
if selectedTab == .home { Image("shouye-b")
} else {
Image("shouye-a")
}
Text("首页")
}
MallView().tag(Tab.mall) .tabItem {
if selectedTab == .mall { Image("jfsc-b")
} else {
Image("jfsc-a")
}
Text("积分商城")
}
MyView().tag(Tab.my) .tabItem {
if selectedTab == .my { Image("user_b")
} else {
Image("user_a")
}
Text("我的")
}
}.accentColor(Color.orange)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
方法二、重新布局底部item,页面事件切换绑定系统的方法。适合有特殊按钮的tabbar场景。
参考:SwiftUI自定UITabBar
import SwiftUI
struct ContentView: View {
enum Tab: Int {
case home, mall, my
}
@State var selectedTab = Tab.home
func tabbarItem(text: String, img: String, tab:Tab, selectedImg:String) -> some View {
VStack(spacing: 0) {
Image(selectedTab == tab ? selectedImg : img).imageScale(.large)
Text(text)
.font(Font.system(size: 13)).foregroundColor(selectedTab == tab ? Color.orange : Color.gray)
.padding(.top, 3)
}.frame(width: UIScreen.main.bounds.size.width / 3, height: 49, alignment: .center).background(Color.white)
}
var body: some View {
NavigationView {
ZStack(alignment: .bottom) {
TabView(selection: $selectedTab) {
HomeView().tag(Tab.home) //自定义的内容view
MallView().tag(Tab.mall)//自定义的内容view
MyView().tag(Tab.my)//自定义的内容view
}
HStack(alignment: .center, spacing: 0) {
self.tabbarItem(text: "首页", img: "shouye-a", tab: Tab.home, selectedImg: "shouye-b").onTapGesture {
selectedTab = .home
}
self.tabbarItem(text: "积分商城", img: "jfsc-a", tab: Tab.mall, selectedImg: "jfsc-b").onTapGesture {
selectedTab = .mall
}
self.tabbarItem(text: "我的", img: "user_a", tab: Tab.my, selectedImg: "user_b").onTapGesture {
selectedTab = .my
}
}
}
}
}
}
网友评论