我有以下简单的SwiftUI视图,其中包含一个组件,该组件包含带有复选框的营销偏好选项列表和更新偏好的按钮:
@StateObject var marketingPreferencesViewModel: MarketingPreferencesViewModel
var body: some View {
VStack {
MarketingPreferencesView(viewModel: .init())
Button {
marketingPreferencesViewModel.marketingUpdateRequested()
} label: {
Text("Update prefs")
}
}
}
市场偏好视图如下:
struct MarketingPreferencesView: View {
@ObservedObject var viewModel: MarketingPreferencesViewModel
var body: some View {
VStack(alignment: .leading) {
marketingPreference(type: .email)
marketingPreference(type: .directMail)
marketingPreference(type: .notification)
marketingPreference(type: .sms)
marketingPreference(type: .telephone)
}
}
func marketingPreference(type: MarketingOptions) -> some View {
HStack {
if viewModel.preferencesAreLoading {
ProgressView()
} else {
Button {
switch type {
case .email:
viewModel.emailMarketingEnabled.toggle()
case .notification:
viewModel.notificationMarketingEnabled.toggle()
case .sms:
viewModel.smsMarketingEnabled.toggle()
case .telephone:
viewModel.telephoneMarketingEnabled.toggle()
case .directMail:
viewModel.directMailMarketingEnabled.toggle()
}
} label: {
switch type {
case .email:
viewModel.emailMarketingEnabled ? Image.General.Checkbox.checked : Image.General.Checkbox.unChecked
// ... remaining switch cases follow same pattern
}
}
}
Text(type.title())
}
.padding(.bottom, Constants.bottomPadding)
}
}
市场偏好视图模型:
class MarketingPreferencesViewModel: ObservableObject {
@Published var emailMarketingEnabled = false {
didSet {
print(emailMarketingEnabled)
}
}
@Published var directMailMarketingEnabled = false
@Published var notificationMarketingEnabled = false
@Published var smsMarketingEnabled = false
@Published var telephoneMarketingEnabled = false
private func updateMarketingPreferences() {
// For now, just printing emailMarketingEnabled value for debugging
print(emailMarketingEnabled)
}
func marketingUpdateRequested() {
self.updateMarketingPreferences()
}
}
}
因此,用户点击营销偏好按钮,这会在视图模型中切换相应的值。
然而,由于某种原因,当我使用marketingUpdateRequested((方法时,如果我检查emailMarketingEnabled的值,即使我已经切换了它,它也总是错误的。
复制步骤:
- 点击emailMarketingEnabled按钮
- "true"打印在控制台中
- 点击"更新首选项"按钮
- 打印"false">
我已经将didSet放在emailMarketingEnabled属性上,看看它是否在其他地方发生了更改,但它没有。为什么,一旦我设置为true,当我点击按钮时,这是false?
您需要实例化MarketingPreferencesViewModel
,然后将其传递给MarketingPreferencesView
,类似于下面的示例代码:
// -- here
@StateObject var marketingPreferencesViewModel = MarketingPreferencesViewModel()
var body: some View {
VStack {
MarketingPreferencesView(viewModel: marketingPreferencesViewModel) // <-- here
Button {
marketingPreferencesViewModel.marketingUpdateRequested()
} label: {
Text("Update prefs")
}
}
}