
- SwiftUI - Home
- SwiftUI - Overview
- SwiftUI vs UIkit
- SwiftUI Environment
- SwiftUI - Environment Setup
- SwiftUI - Basic Components
- SwiftUI - Building First Application
- SwiftUI Views
- SwiftUI - Views
- SwiftUI - Customize Text View
- SwiftUI - Custom Image View
- SwiftUI - Stacks
- SwiftUI Drawing Shapes
- SwiftUI - Shapes
- SwiftUI - Drawing line
- SwiftUI - Drawing Rectangle
- SwiftUI - Drawing Rounded Rectangle
- SwiftUI - Drawing Triangle
- SwiftUI - Drawing Circle
- SwiftUI - Drawing Star
- SwiftUI - Drawing Polygon
- SwiftUI - Drawing Pie chart
- SwiftUI - Using built-in shapes
- SwiftUI - Text
- SwiftUI - Text View
- SwiftUI - Text Input and Output
- SwiftUI - Color
- SwiftUI - Color
- SwiftUI - Colorpicker
- SwiftUI - Gradients
- SwiftUI - Adjust Color
- SwiftUI - Effects
- SwiftUI - Effects
- SwiftUI - Blend Effect
- SwiftUI - BLur Effect
- SwiftUI - Shadow Effect
- SwiftUI - Hover Effect
- SwiftUI - Animations
- SwiftUI - Animations
- SwiftUI - Creating Animations
- SwiftUI - Creating an Explicit Animation
- SwiftUI - Multiple Animations
- SwiftUI - Transitions
- SwiftUI - Asymmetric Transition
- SwiftUI - Custom Transition
- SwiftUI - Image
- SwiftUI - Images
- SwiftUI - Image as Background
- SwiftUI - Rotating Image
- SwiftUI - Media
- SwiftUI - View Layout
- SwiftUI - View Layout
- SwiftUI - View Size
- SwiftUI - View Spacing
- SwiftUI - View Padding
- SwiftUI - UI Controls
- SwiftUI - UI Controls
- SwiftUI - Button
- SwiftUI - CheckBox
- SwiftUI - Menubar
- SwiftUI - Toolbar
- SwiftUI - Search Bar
- SwiftUI - TextField
- SwiftUI - Slider
- SwiftUI - Toggle
- SwiftUI - Pickers
- SwiftUI - Menus
- SwiftUI - List & Tables
- SwiftUI - Lists
- SwiftUI - Static List
- SwiftUI - Dynamic List
- SwiftUI - Customize List
- SwiftUI - Tables
- SwiftUI - Forms
- SwiftUI - Forms
- SwiftUI - Breaking Forms in Sections
- SwiftUI - Event Handling
- SwiftUI - Event Handling
- SwiftUI - Gesture
- SwiftUI - Clipboard
- SwiftUI - Drag and Drop
- SwiftUI - Focus
- SwiftUI - Alert
- SwiftUI - Miscellaneous
- SwiftUI - Containers
- SwiftUI - Navigation
- SwiftUI - Notifications
- SwiftUI - Cross-Platform UI
- SwiftUI - Data
- SwiftUI - Accessibility
- SwiftUI - Framework Integration
- SwiftUI - Framework Integration
- SwiftUI - Interfacing with UIKit
- SwiftUI - Creating macOS App
- SwiftUI Useful Resources
- SwiftUI - Useful Resources
- SwiftUI - Discussion
SwiftUI - Event Handling
Event handling is a process in which we capture an event and then respond to that event either using taps, gestures, long press, etc. SwiftUI supports various mechanisms to handle events and can trigger actions according to the interaction of the user.
Unlike traditional UI frameworks that use heavy methods or delegates to handle events, SwiftUI uses lightweight approaches to handle events. In other words, in SwiftUI, rather than creating separate event listeners we can directly define an event handler in the user interface code.
SwiftUI handles events by combining view modifiers, state management and gestures so that it can easily track the event and respond to it quickly. The declarative approach of SwiftUI makes it much more readable and can require less code to handle events as compared to traditional frameworks.
Type of Events in SwiftUI
SwiftUI supports various types of events which allow developers to respond to various user interactions. Some of the common events are as follows.
-
Button Action: It is the most commonly used action handler. It allows users to respond to it by clicking or tapping on it. It is an in-built event handler and it comes with an action parameter that defines what will happen when the button is pressed. So whenever the user presses on the button it will always act.
For example, a form has a submit button, so whenever the user clicks on the submit button all the data entered in the fields will be sent to the server for storage. So here clicking on the button is the action and sending data to the server is the response to that action.
-
Gesture: Just like button gesture is also the most commonly used event handler. Gesture is a touch or motion-based interaction such as taps, swipes, pinches, drags, long presses, etc.
It can handle user interaction using these gestures. For example, whenever a user presses long on the screen a list of elements will display so that it can select any action from that list. So here long press is the gesture and the display list is the response to that gesture.
State-Based Events: In SwiftUI, we are allowed to create state-based events using @State and @Binding. It updates the state property whenever any change happens.
Appear and Disappear Events: It handles how views appear or disappear from the screen with the help of .onAppear and .onDisappear modifiers.
Scroll Events: It responds to the user interactions with a scrollable view. It uses ScrollViewReader to handle the scroll position.
Drag and Drop Event: This event supports drag and drop interaction in the app. It allows users to drag any item from the view and drop it anywhere inside and outside the app.
Input Event: This event allows the user to enter data or interact with the user by entering data in the given text field, slider, toggle, etc. It also allows the app to respond to what the user is typing, selecting or modifying. SwiftUI provides various modifiers to capture, respond and manage input events.
How to Handle Events in SwiftUI
In SwiftUI, we can handle events with the help of actions and gestures such as taps, drags, long presses, etc. Some of the commonly used methods to handle events are as follows −
Button Taps
Button tap event is handled by the action parameters that come with the Button() method. This parameter holds what action will be performed whenever the button is clicked or tapped. A single view can have multiple buttons.
Example
The following SwiftUI program to used to display data whenever we click on the display button.
import SwiftUI struct ContentView: View { @State private var input: String = "" @State private var result: String = "" var body: some View { VStack { TextField("Enter Your Name", text: $input).padding() Button(action: { // Update the output string with the input string result = input // Clear the field input = "" }) { Text("Submit") .padding() .background(.brown) .foregroundStyle(.white) .cornerRadius(10) }.padding() // Display entered data if !result.isEmpty { Text("Output Data: \(result)").font(.title3) } } } } #Preview { ContentView() }
Output

Gesture Modifiers
SwiftUII provide various gesture handlers such as TapGesture, LongPressGesture, DragGesture, etc. Each gesture is attached to any view to handle the specified interaction such as tapGesture handles single or multiple taps on the view, longPressGesture handles whenever the user presses long on the screen, etc.
Example
The following SwiftUI program changes the color of the text when the user taps on it.
import SwiftUI struct ContentView: View { @State private var myColor: Color = .red var body: some View { Text("Tap me to see the magic") .font(.title) .foregroundStyle(myColor) // The color of the text will change // to blue when the user tap on it .onTapGesture { myColor = .blue } } } #Preview { ContentView() }
Output

Appear and Disappear Events
This event is used whenever we want to display or disappear some view from the container or parent view or screen. It can be handled with the help of .onAppear and .onDisappear modifiers. The.onAppear modifier is used when we want to display a view whereas the .onDisappear modifier is used whenever we clean up resources or save data.
Example
The following SwiftUI program to apply the appear and disappear event.
import SwiftUI struct ContentView: View { @State private var myText: String = "Hello" @State private var Visibility: Bool = true var body: some View { VStack { if Visibility { Text(myText) .font(.title) .padding() .onAppear { // Action when the text appears print("Display Text") myText = "Welcome to TutorialsPoint" } .onDisappear { // Action when the text disappears print("Remove Text") myText = "Not Found" } } Button(action: { // Toggle visibility Visibility.toggle() }) { Text(Visibility ? "Hide Text" : "Display Text") .padding() .background(.blue) .foregroundStyle(.white) } } } } #Preview { ContentView() }
Output

@State and @Binding for Interactive Events
In the state-based event, we use @State and @Binding to record the change in the state of the view. It will automatically update the state according to the change.
Example
The following SwiftUI program used state and binding for the slider component.
import SwiftUI struct ContentView: View { // State variable @State private var value: Double = 1.0 var body: some View { VStack { Text("Adjust the slider:").font(.title) Slider(value: $value, in: 1...5).padding() // Passing slider into the new view using a binding newView(value: $value) } } } struct newView: View { // Binding variable to receive from the parent view @Binding var value: Double var body: some View { Text("Selected Value: \(value, specifier: "%.2f")") .font(.title) } } #Preview { ContentView() }
Output

Drag and Drop Event
The drag and drop event is used to drag a view or component from one view and drop it to another location or view. The .onDrag modifier is used to drag data whereas the .onDrop modifier is used to handle how the data will dropped.
Example
The following SwiftUI program to used to drag a circle from one location to another.
import SwiftUI struct ContentView: View { // Track the position @State private var position = CGSize.zero // Track the dragged offset @State private var dragOffsetValue = CGSize.zero var body: some View { VStack { Text("Drag the circle") .font(.title) // Draggable Circle Circle() .fill(.mint) .frame(width: 100) .offset(x: position.width + dragOffsetValue.width, y: position.height + dragOffsetValue.height) .gesture( DragGesture() .onChanged { g in // Update the offset value during the drag dragOffsetValue = g.translation } .onEnded { _ in // Update position after the drag is finished. position.width += dragOffsetValue.width position.height += dragOffsetValue.height dragOffsetValue = .zero } ) .animation(.easeIn, value: position) } } } #Preview { ContentView() }
Output

Input Event
We can handle input events using various UI components such as TextField, Toggle, Slider, etc. These UI components take input from the user and use state binding and other modifiers like .onSubmit, .onChange, etc., to handle the change in state and user response.
Example
The following SwiftUI program displays the entered data.
import SwiftUI struct ContentView: View { @State private var name: String = "" var body: some View { VStack { // For input TextField("Enter your name", text: $name) .padding(10) // Display Entered Data Text("Entered Data: \(name)!") } .padding() } } #Preview { ContentView() }
Output
