0Pricing
SwiftUI Academy · Lección

Vincular vistas a ViewModels

Controle la vista mediante las propiedades del view model.

Vincular vistas a ViewModels es una lección gratuita de SwiftUI Academy en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de SwiftUI Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de SwiftUI Academy incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Owning the ViewModel

The view that creates a ViewModel owns it. Use @State to hold the instance so it survives across re-renders of the view.

@State private var vm = ProfileViewModel()

Reading State in body

Inside body, read the ViewModel properties like normal values. SwiftUI re-runs body whenever those observed properties change.

Text(vm.greeting)

Calling Actions on Tap

Wire a button action straight to a ViewModel method. The view stays simple, just forwarding the intent to the brain.

Button("Reload") {
    vm.load()
}

Driving Conditional UI

Let ViewModel state choose the layout. Switch on isLoading to show a spinner or the content with no extra view logic.

if vm.isLoading {
    ProgressView()
} else {
    Text(vm.greeting)
}

Two-Way Fields

For text input, bind a TextField to a ViewModel property with the dollar sign. Edits flow back into the ViewModel instantly.

TextField("Name", text: $vm.name)

Loading When the View Appears

Use the .task modifier to call the ViewModel as the view shows up, kicking off the first data load automatically.

.task {
    await vm.load()
}

Lists From the ViewModel

Feed a List from a ViewModel array. When the model updates its items, SwiftUI diffs the rows and animates the change for you.

List(vm.items) { item in
    Text(item.title)
}

Keep the View Declarative

A well-bound view reads like a sentence: show this state, run that action. No calculations sneak into the body.

Passing the ViewModel Down

Child views can take a ViewModel as a plain property. The parent owns it; children just read and call its methods.

DetailView(vm: vm)

Previews Love ViewModels

In a preview, hand the view a ViewModel filled with sample data. You can showcase loading, empty, and full states side by side. 👀

A Bound Screen at a Glance

This view owns a ViewModel, shows its greeting, and reloads on tap, a complete binding in just a few lines of SwiftUI.

Text(vm.greeting)
Button("Reload") { vm.load() }

Quick Check

How should a view own a fresh ViewModel instance?

Recap: Binding Views to ViewModels

You connected a view to its ViewModel with @State, read its properties in body, and routed taps and input back to it. Next: dependency injection.

Preguntas frecuentes

¿La lección «Vincular vistas a ViewModels» es gratis?

Sí — el texto completo de «Vincular vistas a ViewModels» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de SwiftUI Academy, actualiza a CoddyKit PRO. El curso de SwiftUI Academy incluye 4 lecciones en total.

¿Qué aprenderé en «Vincular vistas a ViewModels»?

Controle la vista mediante las propiedades del view model. Practicas SwiftUI Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar SwiftUI Academy?

No se requiere experiencia previa. SwiftUI Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.

¿Cuánto tiempo toma la lección «Vincular vistas a ViewModels»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de SwiftUI Academy?

Sí. Cada lección de SwiftUI Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Por qué MVVM encaja con SwiftUI
  2. Diseñar un ViewModel
  3. Vincular vistas a ViewModels
  4. Inyección de dependencias para ViewModels
← Volver a SwiftUI Academy