如何解决SwifUI:将存储的值通过用户默认值传递给另一个视图
我使用用户默认值来保存表单中的值。我希望将其中一个价值观(“国籍”)传递给另一个观点。
为此,我尝试使用视图模型,但在我希望传递此数据的文本中得到一个空值。
先来看看表格
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","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")
}
}
解决方法
在提供的场景中,最好使用共享的 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"
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。