【发布时间】:2021-05-15 19:57:43
【问题描述】:
我正在尝试刷新 SwiftUI 中的正文部分。我想这样做,因为人们可以更改天气应该在的位置,并且我希望用户能够刷新并查看新位置的天气,而无需关闭应用程序并重新打开。 我试过设置一个@State 变量,但这也不起作用。 代码如下:
var body: some View {
let test = TestCall2(string: "a")
ZStack {
BackgroundView(isNight: $isNight)
VStack {
let defaults = UserDefaults.standard
let country = defaults.string(forKey: "Country") ?? "England"
let city = defaults.string(forKey: "City") ?? "London"
let name = "\(city), \(country)"
CityName(name: name).id("yes")
MainTemp(weatherIcon:
isNight ? "moon.stars.fill" : "cloud.sun.fill", temp: Int(data.temp.temp)).id("yes")
HStack(spacing: 20) {
WeatherDayView(dayOfWeek: TestCall(string: "Mon"),
imageName: CalledOnceLoaded(string: "cloud.sun.fill"),
temperature: 12)
WeatherDayView(dayOfWeek: "Tue",
imageName: "cloud.fill",
temperature: 14)
WeatherDayView(dayOfWeek: "Wed",
imageName: "cloud.sun.rain.fill",
temperature: 17)
WeatherDayView(dayOfWeek: "Thur",
imageName: "cloud.heavyrain.fill",
temperature: 8)
WeatherDayView(dayOfWeek: "Fri",
imageName: "sun.max.fill",
temperature: 19)
}.id("yes")
Spacer()
let defaults = UserDefaults.standard
let country = defaults.string(forKey: "Country") ?? "England"
let city = defaults.string(forKey: "City") ?? "London"
Button {
getData(city: city, country: country)
DispatchQueue.main.async {
self.change.toggle()
print(self.change)
}
} label: {
FormattedButton(text: "Refresh", textColor: .blue, backgroundColor: .white)
}
Spacer()
}
}
}
Here 是我尝试刷新它的视频。
【问题讨论】:
-
您可以通过更新包装为
@State、@StateObject或类似名称的属性来刷新视图。如果您不了解它们,那么我建议您进行一些研究 -
数据从何而来?如果它来自一个类,您是否尝试过使其符合 ObservableObject 并使用@StateObject?不要忘记使用@Published 将您的变量发布!
-
以上是很好的建议。此外,您没有在示例中提供足够的代码来诊断它为什么不起作用。在此处发帖时,请尝试添加minimal reproducible example。