使用SwiftUI从UserDefaults中的1个以上TextField中保存字符串

时间:2020-02-18 18:59:20

标签: ios swiftui settings user-data userdefaults

我不知道如何为多个文本字段保存userData。

我设法为1个Textfield保存了数据,但是如果我“复制”了代码和Textfield,则只保存了一个textfield userData ...

我的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

如果有一个用于整个user的更简单的解决方案,我将非常感谢您的输入。

谢谢,

1 个答案:

答案 0 :(得分:0)

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) ?? "" {
    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!

}

ContentView:

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))