0Pricing
SwiftUI Academy · Lección

Ejecución de código al pulsar

Imprima, cuente y active lógica al pulsar.

Ejecución de código al pulsar 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.

The Action Is Yours

The closure inside a button is where your app does real work. This is where you run logic, update data, or kick off a task on tap. ⚡

Printing for a Quick Test

The simplest action is a print. It writes to Xcode's console so you can confirm a tap was registered while you build.

Button("Test") {
    print("Button was tapped")
}

Changing a Value

Most actions change some data. Here we bump a count each tap. Soon you will store that value in state so the UI can react.

Button("Add one") {
    count += 1
}

Calling Your Own Function

Keep buttons readable by moving logic into a function. The action becomes a single clear line that names what happens.

Button("Submit") {
    submitForm()
}

Multiple Steps in One Tap

An action can run several lines in order. SwiftUI runs them top to bottom, so a single tap can do a small sequence of work.

Button("Reset") {
    score = 0
    message = "Cleared"
}

Conditional Logic on Tap

You can branch inside the action with an if. The tap decides what to do based on the current values of your data.

Button("Toggle") {
    if isOn { turnOff() } else { turnOn() }
}

Reading and Updating Together

A common pattern reads a value, computes something, then stores it back. The tap captures the user's intent in one place.

Button("Double it") {
    total = total * 2
}

Starting Async Work

For slow work like a network call, wrap it in a Task so the tap stays responsive while the work runs in the background.

Button("Load") {
    Task { await fetchData() }
}

Keep the Action Light

Buttons feel snappy when actions stay short. Hand heavy work to a function or Task instead of writing long logic inline.

One Tap, One Run

The action runs once per tap. If you need repeats, you control that in your logic. SwiftUI never fires the action twice for one tap.

Debugging a Silent Button

If a tap seems to do nothing, drop a print at the top of the action. Seeing it in the console confirms the button is wired correctly.

Button("Why?") {
    print("I ran")
    doWork()
}

Quick Check

Let's check how tap actions behave.

Recap

Well done! A tap can print, change values, branch with if, or start a Task. Keep actions light and call functions for bigger jobs. ⚡

Preguntas frecuentes

¿La lección «Ejecución de código al pulsar» es gratis?

Sí — el texto completo de «Ejecución de código al pulsar» 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 «Ejecución de código al pulsar»?

Imprima, cuente y active lógica al pulsar. 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 «Ejecución de código al pulsar»?

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. Creación de un botón pulsable
  2. Personalización de botones
  3. Ejecución de código al pulsar
  4. Desactivar y activar botones
← Volver a SwiftUI Academy