I tried to implement code of @kentrobin which allowed user to return to root view in a navigation stack if tabview is clicked again.
Code : https://kentrobin.com/home/tap-tab-to-go-back/
Here is my implementation
import SwiftUI
import Combine
struct ContactView: View {
@StateObject var viewModel: ContactViewModel = .init()
let subject: PassthroughSubject<HomeViewModel.Tab, Never>
@State private var searchTerm = ""
@State private var people: [ContactsData] = personsData
var filteredSearch: [ContactsData] {
guard !searchTerm.isEmpty else { return people }
return people.filter {
$0.name.localizedCaseInsensitiveContains(searchTerm)
}
}
var groupedPeople: [(key: String, value: [UUID])] {
Dictionary(grouping: people, by: { $0.affiliation })
.mapValues { value in value.map { $0.id } }
.sorted(by: { $0.key < $1.key })
}
var body: some View {
NavigationStack(path: $viewModel.path){
VStack {
List{
ForEach(Division.allCases, id:\.self){ division in
Section(header: Text(division.rawValue)){
ForEach(personsData, id:\.self){ person in
if person.affiliation == division.rawValue {
NavigationLink(destination: ContactContentView(contact: person)){
ContactCardView(contact: person)
}
.onAppear(){
print("showing contact CARD for \(person.name)")
}
}}
}
}
}
}
.navigationTitle("Contacts")
.onReceive(subject) { tab in
if case .contactBook = tab { viewModel.tabBarTapped() }
}
}
}
}
struct ContactContentView: View {
let contact: ContactsData
var body: some View {
ZStack {
Color(contact.coat)
.ignoresSafeArea(edges: .top)
VStack {
Text(contact.name)
Text(contact.contactNumber)
Text(contact.address)
}
}
.onAppear(){
print("opened view \(contact.name)")
}
}
init(contact: ContactsData) {
self.contact = contact
}
}
struct ContactCardView: View {
let contact: ContactsData
var body: some View {
VStack(alignment: .leading) {
Text(contact.name)
Text(contact.contactNumber)
.font(.subheadline)
.foregroundColor(.secondary)
}
}
init(contact: ContactsData) {
self.contact = contact
}
}
struct ContactsData : Identifiable, Hashable {
var id = UUID()
var name: String
var contactNumber: String
var address: String
var coat: Color
var affiliation: String
}
and the data is like this
let personsData = [
ContactsData(name: "William Jobs", contactNumber: "256-789-0121", address: " NY", coat: .gold, affiliation: "Teacher"),
ContactsData(name: "Jane Smith", contactNumber: "456-789-0123", address: "456 Oak St, Townburg", coat: .purple, affiliation: "Librarian")]