【问题标题】:SwifUI : pass a stored value (via user defaults) to another viewSwiftUI:将存储的值(通过 userdefaults)传递给另一个视图
【发布时间】:2021-04-21 22:45:15
【问题描述】:

我使用用户默认值来保存表单中的值。我希望将其中一个值(“国籍”)传递给另一个视图。

我尝试使用视图模型来执行此操作,但我在希望传递此数据的文本中得到一个空值。

首先看一下表格

import SwiftUI

struct ProfilePageView: View {
    @ObservedObject var viewModel = ViewModel()
    
    var body: some View {
        Form {
            Section(header: Text("Personal Ifo")) {
                TextField("User Name", text: $viewModel.userName)
                
            }
            //
            Section(header: Text("Your Nationality")) {
                Picker(selection: $viewModel.nationality, label: Text("You were born in")) {
                    ForEach(viewModel.nationalities, id: \.self) { nationality in
                        Text(nationality)
                    }
                    
                }
            } //nationality section end
            //
            Section(header: Text("Country of residence")) {
                Picker(selection: $viewModel.countryOfResidence, label: Text("Where do you live ?")) {
                    ForEach(viewModel.countriesOfResidence, id: \.self) { residence in
                        Text(residence)
                    }
                }
            } // country of residence section end
            //
            
        }
        .navigationTitle("Profile")
        //form end
        
    }
}

第二个是我的视图模型,它使我能够将表单值保存为用户默认值

import Foundation

class ViewModel: ObservableObject {
    @Published var userName: String {
        didSet {
            UserDefaults.standard.setValue(userName, forKey: "username")
        }
    }
    //nationality
    @Published var nationality: String {
        
        didSet {
            UserDefaults.standard.setValue(nationality, forKey: "nationality")
        }

    }
    public var nationalities = ["USA", "Japan", "Senegal", "France"]
    
    //country of residence
    @Published var countryOfResidence: String {
        didSet {
            UserDefaults.standard.setValue(countryOfResidence, forKey: "country of residence")
        }
    }
    public var countriesOfResidence = ["USA", "Japan", "Senegal", "France"]
    
    init() {
        self.userName = UserDefaults.standard.object(forKey: "username") as? String ?? ""
        self.nationality = UserDefaults.standard.object(forKey: "nationality") as? String ?? ""
        self.countryOfResidence = UserDefaults.standard.object(forKey: "Coutry of residence") as? String ?? ""
    }
}

最后是我希望附加此值的视图。我正在使用@observedObject 来尝试从我的视图模型中检索“国籍”值。但是该值未在文本中传递

import SwiftUI

struct VisaPolicyDetailView: View {
    
    @Binding var country: Country
    @ObservedObject var viewmodel = ViewModel()
    
    var body: some View {
        VStack(alignment: .leading,spacing: 20) {
            //a dismiss button
            HStack {
                Spacer()
                Image(systemName: "xmark")
                    .renderingMode(.original)
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(width: 40, height: 40)
            }
            
            Spacer()
            
            Text(country.countryName)
                .font(.title)
                .fontWeight(.medium)
            Text("Visa policy for \(viewmodel.nationality) : visa policy")
                .font(.title2)
            
            Spacer()
        }
        .padding()
        .navigationTitle("Visa Policy Detail")
    }
}

【问题讨论】:

    标签: swift forms swiftui userdefaults


    【解决方案1】:

    在提供的场景中,最好使用共享ViewModel,比如

    class ViewModel: ObservableObject {
       static let shared = ViewModel()
    
       // .. other code
    }
    

    并在所有受影响的视图中使用 shared

    struct ProfilePageView: View {
        @ObservedObject var viewModel = ViewModel.shared  // << here !!
    ...
    

    struct VisaPolicyDetailView: View {
        
        @Binding var country: Country
        @ObservedObject var viewmodel = ViewModel.shared  // << here !!
    ...
    

    那么两个视图都会观察到ViewModel 的同一个实例。

    SwiftUI 2.0:使用AppStorage 自动存储/观察用户默认值,例如

    @AppStorage("nationality") var nationality = "some default here"
    

    【讨论】:

      猜你喜欢
      • 2021-06-12
      • 1970-01-01
      • 1970-01-01
      • 2013-08-29
      • 1970-01-01
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多