【问题标题】:How to refresh the body in SwiftUI如何在 SwiftUI 中刷新 body
【发布时间】: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

标签: swift swiftui


【解决方案1】:

我找到了解决办法!这有点hacky,但它有效。我有一个名为 isNight 的布尔值,它启用夜间模式,它在正文部分被调用。为了让它更新,我只是切换了两次,夜间模式没有任何反应,但身体更新了。希望这对人们有所帮助

【讨论】:

    猜你喜欢
    • 2021-07-08
    • 2021-07-25
    • 2021-05-22
    • 2022-12-07
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多