onAppear delay in SwiftUI with example
In this tutorial, I will show you how to add delay to onAppearin SwiftUI. If you are trying to load a view or anything with .onAppear but still you want some delay in execution you are at the right place.
Let’s take this small example:
import SwiftUI
struct ContentView: View {
@State private var isVisible = false
var body: some View {
VStack {
Text("Hello, SwiftUI!")
.font(.largeTitle)
.onAppear {
isVisible = true
}
if isVisible {
Text("View is now visible!")
.foregroundColor(.green)
}
}
}
}

Now if you wish to load Text("View is now visible!") this after a few seconds then you just need to add this line inside onAppear just like this:
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
isVisible = true
}
}Full code:
import SwiftUI
struct ContentView: View {
@State private var isVisible = false
var body: some View {
VStack {
Text("Hello, SwiftUI!")
.font(.largeTitle)
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
isVisible = true
}
}
if isVisible {
Text("View is now visible after delay!")
.foregroundColor(.green)
}
}
}
}
Output:
This will load the text after 2 seconds. So you can add delay by changing the value as per your needs.
You can also check: How to add a delay to code execution in Swift
Leave a Reply