Hello together,
i do have a navigation view
struct SettingsView: View {
private let choices = [
Choice(imgName: "flag", topic: "Country / League"),
Choice(imgName: "square.and.pencil", topic: "Scoring"),
Choice(imgName: "tv.and.mediabox", topic: "Scoreboard"),
Choice(imgName: "person", topic: "Profile settings"),
Choice(imgName: "info.circle", topic: "Information")
]
@State private var selectedSetting: Choice?
var body: some View {
NavigationView {
VStack{
List(choices) { choice in
NavigationLink(
tag: choice,
selection: $selectedSetting,
destination: {
DetailSettingsView(arg: "\(choice.topic)")
}, label: {
HStack {
Image(systemName: choice.imgName)
.resizable()
.scaledToFit()
.frame(width: 24)
.padding(.trailing)
Text("\(choice.topic)")
.font(.body)
Spacer()
}
}
)
}
}
}
}
}
destination points to a DetailSettingsView:
struct DetailSettingsView: View {
// Store Settings by using class UserDefaults
@AppStorage("country") var country: String = ""
@AppStorage("club") var club: String = ""
@EnvironmentObject var model: ContentModel
@EnvironmentObject var settings: AppSettings
let arg: String
var body: some View {
if arg == "Country / League" {
VStack {
Form {
Section(header: Text("Select Country and App-Language")) {
Picker ("Country", selection: $country) {
ForEach(model.countries) { arg in
Text(arg.name).tag(arg.id)
}
}
.onChange(of: country, perform: { value in
print(value)
model.getClubsInCountry(country: value)
if model.clubs.count > 0 {
club = model.clubs.first!.name
}
})
}
Section(header: Text("Select Your Home Club")) {
Picker ("Club", selection: $club) {
ForEach(model.clubs) { arg in
Text(arg.name).tag(arg.id)
}
}
}
}
}
}
else if arg == "Scoring" {
// ...
}
else if arg == "Scoreboard" {
Text("efg")
}
}
}
All Data’s are fetched from a Firestore database.
class ContentModel: ObservableObject {
// Reference to Cloud Firestore database
let db = Firestore.firestore()
@Published var countries = [Country]()
func getSupportedCountries() {
// Get a referene to the countries collection
let db = Firestore.firestore()
db.collection("countries")
.getDocuments { snapshot, error in
// Check there's no errors
if error == nil {
// Declare temp country list
var temp = [Country]()
for doc in snapshot!.documents {
var m = Country(id: doc["id"] as? String ?? "",
name: doc["name"] as? String ?? "",
language: doc["language"] as? String ?? "")
temp.append(m)
}
DispatchQueue.main.async {
self.countries = temp
}
}
}
}
}
The problem I’m facing right now is, that when .onChange() applies, because the user has changed the country, new data get fetched from the Firestore database (model.getClubsInCountry(country: value)). After fetching the clubs from the selected country, the DetailSettingsView closes and SettingsView appears again.
Why? how can I enforce Swift to stay in the DetailView after fetching data from Firestore?
Thanks for your help!
Peter