Executando código ao tocar
Imprima, conte e acione lógica a partir de um toque.
Executando código ao tocar é uma aula grátis de SwiftUI Academy no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de SwiftUI Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de SwiftUI Academy inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em 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. ⚡
Perguntas Frequentes
A aula “Executando código ao tocar” é grátis?
Sim — o texto completo de “Executando código ao tocar” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de SwiftUI Academy, atualize para CoddyKit PRO. O curso de SwiftUI Academy inclui 4 aulas no total.
O que vou aprender em “Executando código ao tocar”?
Imprima, conte e acione lógica a partir de um toque. Você pratica SwiftUI Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar SwiftUI Academy?
Nenhuma experiência prévia é necessária. SwiftUI Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.
Quanto tempo leva a aula “Executando código ao tocar”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de SwiftUI Academy?
Sim. Cada aula de SwiftUI Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Criando um botão acionável
- Estilizando botões
- Executando código ao tocar
- Desativando e ativando botões