Skip to content

Instantly share code, notes, and snippets.

@hamsternik
Created April 27, 2022 22:32
Show Gist options
  • Save hamsternik/4077dbda0f8e4e2e7c3e359b89e99e5d to your computer and use it in GitHub Desktop.
Save hamsternik/4077dbda0f8e4e2e7c3e359b89e99e5d to your computer and use it in GitHub Desktop.
Improved implementation considering iOS 15 (latest) update
/// NOTE: based on the StackOverflow answer
/// https://stackoverflow.com/a/60107650/3527499
import SwiftUI
struct TabBarView: View {
var items: [TabBarItem]
@State var selectedIndex = 0
init(_ items: [TabBarItem]) {
self.items = items
}
var body: some View {
ZStack {
ForEach(items.indices) { index in
self.items[index].view
.opacity(self.selectedIndex == index ? 1 : 0)
}
GeometryReader { geometry in
VStack {
Spacer()
ZStack(alignment: .top) {
LinearGradient(
gradient: Gradient(colors: [.black.opacity(0.3), .black.opacity(0.4)]),
startPoint: .top,
endPoint: .bottom
).frame(height: 70 + geometry.safeAreaInsets.bottom)
HStack {
ForEach(self.items.indices) { i in
Button {
withAnimation(.easeInOut) {
self.selectedIndex = i
}
} label: {
VStack {
let imageForegroundColor: Color = self.selectedIndex == i ? .white : .white.opacity(0.4)
self.items[i].image
.foregroundColor(imageForegroundColor)
.padding(.top, 10)
.font(.title)
Text(self.items[i].title)
.foregroundColor(.white)
.font(.system(size: 16, weight: .bold))
.padding(.top, 10)
.opacity(0.5)
}
.frame(maxWidth: .infinity)
}
}
}
}
}
.edgesIgnoringSafeArea(.bottom)
}
}
}
}
struct TabBarItem {
let view: AnyView
let image: Image
let title: String
init<V: View>(view: V, image: Image, title: String) {
self.view = AnyView(view)
self.image = image
self.title = title
}
}
struct TabBarView_Previews: PreviewProvider {
static var previews: some View {
TabBarView([
TabBarItem(
view: Text("This is home screen"),
image: Image(systemName:"house.fill"),
title: "home"
),
TabBarItem(
view: Text("❤️‍🩹"),
image: Image(systemName:"heart.fill"),
title: "favorite"),
])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment