Я хочу знать, какой самый простой способ связать свойство (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
Как связать свойство от ParentViewModel с свойством ChildViewModel ⇐ IOS
Программируем под IOS
-
Anonymous
1747463771
Anonymous
Я хочу знать, какой самый простой способ связать свойство (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)
}
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79623652/how-to-bind-a-property-from-parentviewmodel-to-a-property-of-a-childviewmodel[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия