Используя тот же код, который указан в ссылке, упомянутой в вашем вопросе, я внес небольшие изменения, чтобы принять код для ваших нужд
struct ContentView: View {
@ObservedObject var model = Model()
var body: some View {
NavigationView {
Form {
Section(header: Text("Header").font(.title)) {
Picker(selection: $model.selectedContry, label: Text("Country")){
ForEach(0 ..< model.countryNemes.count){ index in
Text(self.model.countryNemes[index])
}
}
Picker(selection: $model.selectedCity, label: Text("City")){
ForEach(0 ..< model.cityNamesCount){ index in
Text(self.model.cityNames[index])
}
}
.id(model.id)
}
}.navigationBarTitle("Navigation Title")
}
}
}
Пожалуйста, обратите внимание, что в форме нет VStack, но есть раздел! Результат работает как положено. (остальной код без каких-либо изменений). Попробуйте код на реальном устройстве (из-за известной ошибки "кнопка назад" в симуляторе)
![enter image description here](https://i.stack.imgur.com/juQFL.gif)
В случае, если у вас возникли проблемы с остальным кодом вот это
import Foundation
import SwiftUI
struct Country: Identifiable {
var id: Int = 0
var name: String
var cities: [City]
}
struct City: Identifiable {
var id: Int = 0
var name: String
}
class Model: ObservableObject {
let countries: [Country] = [Country(id: 0, name: "USA", cities: [City(id: 0, name: "New York"),City(id: 1, name: "Los Angeles"),City(id: 2, name: "Dallas"),City(id: 3, name: "Chicago")]),Country(id: 1, name: "France", cities: [City(id: 0, name: "Paris")])]
@Published var selectedContry: Int = 0 {
willSet {
print("country changed", newValue, citySelections[newValue] ?? 0)
selectedCity = citySelections[newValue] ?? 0
id = UUID()
}
}
@Published var id: UUID = UUID()
@Published var selectedCity: Int = 0 {
willSet {
DispatchQueue.main.async { [newValue] in
print("city changed", newValue)
self.citySelections[self.selectedContry] = newValue
}
}
}
var countryNemes: [String] {
countries.map { (country) in
country.name
}
}
var cityNamesCount: Int {
cityNames.count
}
var cityNames: [String] {
countries[selectedContry].cities.map { (city) in
city.name
}
}
private var citySelections: [Int: Int] = [:]
}