使用 SwiftUI 在 UserDefaults 中保存来自超过 1 个 TextField 的字符串

Save String from more than 1 TextField in UserDefaults with SwiftUI

我不知道如何为超过 1 个文本字段保存用户数据。

我设法为 1 个文本字段保存了数据,但是如果我 "duplicate" 代码和文本字段,它只会保存一个文本字段 userData...

我的用户数据文件:

import SwiftUI
import Combine

class UserData : ObservableObject {

 private static let userDefaultBuyingPrice = "BuyingPrice"
 private static let userDefaultRent = "Rent"


 @Published var BuyingPrice = UserDefaults.standard.string(forKey: UserData.userDefaultBuyingPrice) ?? ""

  @Published var Rent = UserDefaults.standard.string(forKey: UserData.userDefaultRent) ?? ""
  private var canc: AnyCancellable!

 }

我的 ContentView 文件:

struct ContentView: View {

@ObservedObject var userData = UserData()

var body: some View {
    VStack{
        TextField("BuyingPrice", text: $userData.BuyingPrice)
            .font(.title)
            .keyboardType(.decimalPad)

        TextField("Rent", text: $userData.Rent)
            .font(.title)
            .keyboardType(.decimalPad)
    }
}

}

Only the second value is saved, cannot figure out why the second one is not working

如果有更简单的解决方案来保存整个用户数据,我将不胜感激。

谢谢,

用户数据:

import SwiftUI
import Combine

class UserData : ObservableObject {

  private static let userDefaultBuyingPrice = "BuyingPrice"
  private static let userDefaultRent = "Rent"


  @Published var BuyingPrice = UserDefaults.standard.string(forKey: UserData.userDefaultBuyingPrice) ?? "" {
    didSet {
      UserDefaults.standard.set(self.BuyingPrice, forKey: UserData.userDefaultBuyingPrice)
    }
  }

  @Published var Rent = UserDefaults.standard.string(forKey: UserData.userDefaultRent) ?? "" {
    didSet {
      UserDefaults.standard.set(self.Rent, forKey: UserData.userDefaultRent)
    }
  }
  private var canc: AnyCancellable!

}

内容视图:

import SwiftUI

struct ContentView: View {
  @EnvironmentObject var userData: UserData

   var body: some View {
       VStack{
           TextField("BuyingPrice", text: $userData.BuyingPrice)
               .font(.title)
               .keyboardType(.decimalPad)

           TextField("Rent", text: $userData.Rent)
               .font(.title)
               .keyboardType(.decimalPad)
       }
   }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
      ContentView().environmentObject(UserData())
    }
}

在SceneDelegate.swift中:

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

  var window: UIWindow?
  var userData = UserData() //add this line

//then modify this  line:
window.rootViewController = UIHostingController(rootView: contentView)
//to this:
window.rootViewController = UIHostingController(rootView: contentView.environmentObject(userData))