我在swiftui中有一个选择器,我需要从我当前在我的Mac上托管的json中填充该选择器。
在运行代码时,显示的选择器保持空白,但是数据可用(如果我单击下面的按钮进行打印)。
这是我的代码:
选择器(ContentView.swift):
@State var nwm = NetworkManager()
...
Picker("Wähle deine Schule", selection: $selectedSchool) {
ForEach(0 ..< nwm.schoolList.results.count) {
Text(self.nwm.schoolList.results[$0].name).tag($0)
}
}.labelsHidden()
NetworkManager.swift:
class NetworkManager : ObservableObject {
var didChange = PassthroughSubject<NetworkManager, Never>()
var schoolList = SchoolList(results: []) {
didSet {
didChange.send(self)
}
}
init() {
guard let url = URL(string: "http://jonasmacbookpro.local:8083/IOSApp/getDKSchools") else { return }
URLSession.shared.dataTask(with: url) {
(data, _, _) in
let schoolList = try! JSONDecoder().decode(SchoolList.self, from: data!)
DispatchQueue.main.async {
self.schoolList = schoolList
}
}.resume()
}
}
School.swift
struct School : Identifiable, Decodable {
let id = UUID()
var name : String
var ort : String
var link : String
}
struct SchoolList: Decodable {
var results: [School]
}
有人知道,为什么它不起作用?
答案 0 :(得分:1)
代替
@State var nwm = NetworkManager()
使用
@ObservedObject var nwm = NetworkManager()
,而不是
var didChange = PassthroughSubject<NetworkManager, Never>() var schoolList = SchoolList(results: []) { didSet { didChange.send(self) } }
使用
@Published var schoolList = SchoolList(results: [])
答案 1 :(得分:0)
要刷新选择器,就是添加一个唯一的ID。您可以将.id(UUID())
添加到选择器中,它应该可以正常工作