Skip to content

Instantly share code, notes, and snippets.

@filimo
Created January 17, 2020 21:46
Show Gist options
  • Save filimo/69e39e6393938a40dc850c79839cd5a0 to your computer and use it in GitHub Desktop.
Save filimo/69e39e6393938a40dc850c79839cd5a0 to your computer and use it in GitHub Desktop.
Custom TabView in SwiftUI
class AdvanceTabViewStore: ObservableObject {
private init() {}
static let shared = AdvanceTabViewStore()
@Published var activeTab = 1
}
struct AdvanceTabView: View {
@ObservedObject var store = AdvanceTabViewStore.shared
var body: some View {
VStack {
AdvanceTabView_Content(tab: 1) { Text("Tab 1") }
AdvanceTabView_Content(tab: 2) { Text("Tab 2") }
AdvanceTabView_Content(tab: 3) { Text("Tab 3") }
AdvanceTabView_Content(tab: 4) { Text("Tab 4") }
AdvanceTabView_Content(tab: 5) { Text("Tab 5") }
HStack {
AdvanceTabView_Item(image: "star.fill", title: "Favorites", tab: 1)
AdvanceTabView_Item(image: "clock.fill", title: "Recents", tab: 2)
AdvanceTabView_Item(image: "person.crop.circle", title: "Contacts", tab: 3)
AdvanceTabView_Item(image: "circle.grid.3x3.fill", title: "Keypad", tab: 4)
AdvanceTabView_Item(image: "recordingtape", title: "Voicemail", tab: 5)
}
}
}
}
struct AdvanceTabView_Content<Content: View>: View {
@ObservedObject private var store = AdvanceTabViewStore.shared
@State private var show = false
private let tab: Int
private let content: () -> Content
init(tab: Int, @ViewBuilder content: @escaping () -> Content) {
self.tab = tab
self.content = content
}
var body: some View {
Group {
if tab == store.activeTab {
self.content()
.frame(maxWidth: .infinity, maxHeight: .infinity)
.offset(x: self.show ? 0 : UIScreen.main.bounds.width)
.onAppear {
withAnimation(.linear(duration: 0.5)) {
self.show = true
}
}
.onDisappear { self.show = false }
}
}
}
}
struct AdvanceTabView_Item: View {
let image: String
let title: String
let tab: Int
var body: some View {
VStack {
ZStack {
Text(" ")
Image(systemName: image)
}
Text(title)
}
.frame(maxWidth: .infinity)
.contentShape(Rectangle())
.onTapGesture {
AdvanceTabViewStore.shared.activeTab = self.tab
}
}
}
struct AdvanceTabView_Previews: PreviewProvider {
static var previews: some View {
AdvanceTabView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment