Я хочу знать, какой самый простой способ связать свойство (age) из родительского ViewModel (ProfileViewModel) до ребенка ViewModel (AgePickerViewModel) Использование макроса @ObServable. Инициализатор.
Есть ли лучший способ сделать это, чем мой пример?import SwiftUI
#Preview {
ProfileView()
}
// Parent ViewModel
@Observable
class ProfileViewModel {
var name: String = "John"
var age: Int = 30
}
// Child ViewModel with its own responsibility
@Observable
class AgePickerViewModel {
var age: Int
var minAge: Int = 1
var maxAge: Int = 120
init(age: Int) {
self.age = age
}
}
// Parent View
struct ProfileView: View {
@Bindable var viewModel = ProfileViewModel()
var body: some View {
VStack(spacing: 20) {
Text("Profile: \(viewModel.name)")
.font(.title)
Text("Age: \(viewModel.age)")
.font(.headline)
// Passing the age binding to the child view
AgePickerView(age: $viewModel.age)
.frame(height: 200)
.padding()
.background(Color.gray.opacity(0.1))
.cornerRadius(10)
}
.padding()
}
}
// Child View with its own ViewModel
struct AgePickerView: View {
// Child has its own ViewModel
var viewModel: AgePickerViewModel
// Takes a binding to the parent's age property
init(age: Binding) {
self.viewModel = AgePickerViewModel(age: age.wrappedValue)
_boundAge = age
}
// Binding to the external value
@Binding private var boundAge: Int
var body: some View {
VStack {
Text("Select Age")
.font(.headline)
.padding(.bottom, 5)
Picker("Age", selection: $boundAge) {
ForEach(viewModel.minAge...viewModel.maxAge, id: \.self) { age in
Text("\(age)").tag(age)
}
}
.pickerStyle(.wheel)
.onChange(of: boundAge) { _, newValue in
// Update the child ViewModel when the bound value changes
viewModel.age = newValue
}
}
}
}
Поэтому я попытался передать привязку , пока он не попадет в детскую просмотр и там теряет соединение при назначении его с.import SwiftUI
#Preview {
ProfileView()
}
@Observable
class ProfileViewModel {
var name: String = "John"
var age: Int = 30
}
@Observable
class AgePickerViewModel {
var age: Int
var minAge: Int = 1
var maxAge: Int = 120
init(age: Binding) {
// HOW TO: Use Binding in an Observable class?
self.age = age.wrappedValue
}
}
struct ProfileView: View {
@Bindable var viewModel = ProfileViewModel()
var body: some View {
VStack(spacing: 20) {
Text("Profile: \(viewModel.name)")
.font(.title)
Text("Age: \(viewModel.age)")
.font(.headline)
AgePickerView(age: $viewModel.age)
.frame(height: 200)
.padding()
.background(Color.gray.opacity(0.1))
.cornerRadius(10)
}
.padding()
}
}
struct AgePickerView: View {
@Bindable var viewModel: AgePickerViewModel
init(age: Binding) {
// Pass to viewModel
self.viewModel = AgePickerViewModel(age: age)
}
var body: some View {
VStack {
Text("Select Age")
.font(.headline)
.padding(.bottom, 5)
Picker("Age", selection: $viewModel.age) {
ForEach(viewModel.minAge...viewModel.maxAge, id: \.self) { age in
Text("\(age)").tag(age)
}
}
.pickerStyle(.wheel)
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/796 ... dviewmodel