Skip to content

Instantly share code, notes, and snippets.

@kishikawakatsumi
Created November 27, 2019 04:51
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kishikawakatsumi/562028c46e7549aba658c88366417f6b to your computer and use it in GitHub Desktop.
Save kishikawakatsumi/562028c46e7549aba658c88366417f6b to your computer and use it in GitHub Desktop.
My SwiftUI TabView
import SwiftUI
struct TabView: View {
var views: [TabBarItem]
@State var selectedIndex: Int = 0
init(_ views: [TabBarItem]) {
self.views = views
}
var body: some View {
ZStack {
ForEach(views.indices) { i in
self.views[i].view
.opacity(self.selectedIndex == i ? 1 : 0)
}
GeometryReader { geometry in
VStack {
Spacer()
ZStack(alignment: .top) {
LinearGradient(gradient: Gradient(colors: [Color.black.opacity(0.5), Color.black.opacity(0)]), startPoint: .top, endPoint: .bottom)
.frame(height: 49 + geometry.safeAreaInsets.bottom)
HStack {
ForEach(self.views.indices) { i in
Button(action: {
self.selectedIndex = i
}) {
VStack {
if self.selectedIndex == i {
self.views[i].image
.foregroundColor(.white)
.padding(.top, 8)
} else {
self.views[i].image
.foregroundColor(Color.white.opacity(0.5))
.padding(.top, 8)
}
Text(self.views[i].title)
.foregroundColor(.white)
.font(Font.system(size: 12, weight: .bold))
.opacity(0)
}
.frame(maxWidth: .infinity)
}
}
}
}
}
.edgesIgnoringSafeArea(.bottom)
.animation(.easeInOut)
}
}
}
}
struct TabBarItem {
var view: AnyView
var image: Image
var title: String
init<V: View>(view: V, image: Image, title: String) {
self.view = AnyView(view)
self.image = image
self.title = title
}
}
@kishikawakatsumi
Copy link
Author

Usage:

struct ContentView: View {
  var body: some View {
    TabView([
      TabBarItem(view: FeedView(),
                 image: Image("house.fill"),
                 title: "Feed"),
      TabBarItem(view: SearchView(),
                 image: Image("loupe"),
                 title: "Explore"),
      TabBarItem(view: CreateView(),
                 image: Image("plus.circle"),
                 title: "Create"),
      TabBarItem(view: LoginView(),
                 image: Image("person.fill"),
                 title: "Profile"),
    ])
  }
}

@francobellu
Copy link

The content of the page is actually not changing when pressing different tabs

@cdedagit
Copy link

cdedagit commented Apr 8, 2022

TabBarItem(view: , will force allocate all the views for each tab :-(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment