Created
August 30, 2023 16:38
-
-
Save Nadohs/6cf27cfd7859e13b750c16c175073144 to your computer and use it in GitHub Desktop.
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
// Single tab item view | |
struct TabItemView: View { | |
// @State private var isSelected: Bool | |
let imgName: String | |
let title: String | |
let isSelected: Bool | |
let action:()->Void | |
init(img:String, title:String, isSelected:Bool=false, action: @escaping ()->Void={}) { | |
self.imgName = img | |
self.title = title | |
self.isSelected = isSelected | |
self.action = action | |
} | |
var body: some View { | |
let titleText = Text(self.title) | |
VStack { | |
Path().background(isSelected ? .blue : .clear) | |
.frame(width: .infinity, height: 10) | |
.padding(EdgeInsets.make(leading: 30, bottom: 10, trailing: 30)) | |
Image(self.imgName, label: titleText) | |
.resizable() | |
.scaledToFit() | |
} | |
.onTapGesture { | |
print("The whole VStack is tappable now! \(self.title)") | |
self.action() | |
// isSelected = !isSelected | |
} | |
} | |
} | |
// Full Tab bar | |
struct TabBarSelectView: View { | |
let viewModel:ViewModel | |
@MainActor | |
init(viewModel:ViewModel) { | |
self.viewModel = viewModel | |
} | |
var tabs = [TabItemView]() | |
var body: some View { | |
//Bottom Tab Bar | |
HStack(spacing: -1) { | |
ForEach(viewModel.segments) { cur in | |
TabItemView(img: cur.imageName, | |
title: cur.title, | |
isSelected: viewModel.selectedIndex == cur.id, | |
action: { | |
viewModel.selectedIndex = cur.id | |
print("cur:\(viewModel.selectedIndex)", viewModel.selectedIndex) | |
}) | |
.frame(maxWidth: .infinity, maxHeight: .infinity) | |
} | |
.padding(EdgeInsets(top: 0, leading: 0, bottom: 10, trailing: 0)) | |
.frame(maxWidth: .infinity, maxHeight: .infinity) | |
} | |
.frame(maxWidth: .infinity, maxHeight: 80) | |
.background(.green) | |
} | |
} | |
// Preview example of setting it up | |
struct TabBarSelectView_Previews: PreviewProvider { | |
static var previews: some View { | |
TabBarSelectView(viewModel: TabBarSelectView.ViewModel(selectedIndex: 0,segments: [ | |
TabBarSegment(id: 0, title: "Camera", imageName: "tab-icon1b", isSelected: true), | |
TabBarSegment(id: 1, title: "Library", imageName: "tab-icon2b"), | |
TabBarSegment(id: 2, title: "Info", imageName: "tab-icon3b") | |
])) | |
} | |
} | |
// ViewModel Definition | |
extension TabBarSelectView { | |
@MainActor class ViewModel: ObservableObject { | |
@Published var selectedIndex = -1 | |
@Published var segments: [TabBarSegment] | |
init(selectedIndex: Int = -1, segments: [TabBarSegment]) { | |
self.selectedIndex = selectedIndex | |
self.segments = segments | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment