Created
November 27, 2019 04:51
-
-
Save kishikawakatsumi/562028c46e7549aba658c88366417f6b to your computer and use it in GitHub Desktop.
My SwiftUI TabView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
The content of the page is actually not changing when pressing different tabs
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
Usage: