0

我一直在使用 @AppStorage 和 UserDefaults 在 SwiftUI 中进行更新。如果我对具有 @AppStorage 包装器的 vie 进行更改,则一切正常。我对如何在全球范围内进行这项工作感到困惑。

我正在使用具有关联的计算属性和格式化程序的结构。这个想法是检查用户默认值并将项目转换为磅或公斤。问题是使用计算属性的视图在更新 UserDefaults 时不会更新。有没有办法创建一个全局更改来更新下面 SecondaryView 中的 weightFormatted?

// 权重结构

struct Weight {
var weight: Double
var weightFormatted: String {
return weightDecimalLbsOrKgFormatted2(weight)
}

// 格式化方法

func weightDecimalLbsOrKgFormatted2(_ lbs: Double) -> String {
    if (!UserDefaults.standard.bool(forKey: "weightInKilograms")) {
        let weightString = decimalFormatterDecimal2(lbs)
        return weightString + "lbs"
        
    } else {
        let kg = toKg(lbs)
        let weightString = decimalFormatterDecimal2(kg)
        return weightString + "kg"
    }
}

// 设置 weightInKilograms 的位置

struct AccountView: View {
    @AppStorage("weightInKilograms") var weightInKilograms = false

    let weight = Weight(weight: 9.0))
    
    var body: some View {
        VStack {
            Text(weight.weightFormatted)
            Toggle(isOn: $weightInKilograms) {
                        Text("Kilograms")
            }
        }
}
}

// 辅助视图未更新

struct SecondaryView: View {

    let weight = Weight(weight: 9.0))
    
    var body: some View {
         Text(weight.weightFormatted)
}
}
4

1 回答 1

1

你的问题是它weight没有被任何状态包裹。

在你的AccountView,给weight一个@State包装:

struct AccountView: View {
  
  @AppStorage("weightInKilograms") var weightInKilograms = false
  
  @State var weight = Weight(weight: 9.0))
  
  var body: some View {
    //...
  }
}

SecondaryView中,确保weight用 包裹@Binding

struct SecondaryView: View {
  
  @Binding var weight: Weight
  
  var body: some View {
    // ...
  }
}

然后,weight作为Binding<Weight>变量传递到SecondaryView您的第一个视图中:

SecondaryView(weight: $weight)

有没有办法创建一个全局更改来更新下面 SecondaryView 中的 weightFormatted?

如果您希望进行全局更改,则应考虑设置全局EnvironmentObject

class MyGlobalClass: ObservableObject {

  // Published variables will update view states when changed.
  @Published var weightInKilograms: Bool
  { get {
    // Get UserDefaults here
  } set {
    // Set UserDefaults here
  }}

  @Published var weight: Weight
}

如果您将MyGlobalClassas的实例传递EnvironmentObject给主视图,然后传递给辅助视图,则对全局实例中的属性所做的任何更改都将通过@Published包装器更新视图的状态:

let global = MyGlobalClass()

/* ... */

// In your app's lifecycle, or where AccountView is instantiated
AccountView().environmentObject(global)
struct AccountView: View {
  @EnvironmentObject var global: MyGlobalClass

  var body: some View {
    // ...
    Text(global.weight.weightFormatted)
    // ...
    SecondaryView().environmentObject(global)
  }
}
于 2021-06-26T15:42:06.530 回答