First impression is the last impression! And the first thing that your user is going to see will be the Splash screen. So let’s learn how to add Splash screen in SwiftUI.
Initial setup
Let’s first create a simple Splash screen in SwiftUI
:
struct SplashView: View {
var body: some View {
VStack {
Text("Awesome Splash Screen!")
.font(Font.largeTitle)
}
}
}
Here, we have created a simple SplashView
with a Text
“Awesom Splash Screen”.
Let’s create our Home screen now:
struct HomeView: View {
var body: some View {
VStack {
List(0..<5) { i in
Text("Item - \(i)")
}
}
}
}
Our HomeView
contains a simple list of dummy items.
Now, We have two views needed for this tutorial: SplashView
& HomeView
.
Let’s do the magic!
The logic of a Splash Screen is to appear for a few seconds on App launch and then show the Landing page of the App, Home or Login Screen, for example.
Let’s use this simple logic and update our SplashView
:
struct SplashView: View {
// 1.
@State var isActive:Bool = false
var body: some View {
VStack {
// 2.
if self.isActive {
// 3.
HomeView()
} else {
// 4.
Text("Awesome Splash Screen!")
.font(Font.largeTitle)
}
}
// 5.
.onAppear {
// 6.
DispatchQueue.main.asyncAfter(deadline: .now() + 2.5) {
// 7.
withAnimation {
self.isActive = true
}
}
}
}
}
Let’s go through the code step by step:
- We introduced a State property,
isActive
, to maintain the state of the view. - We check this State property in our
body
, to render UI accordingly. - If
isActive
istrue
, it means the app is in active state now. So load theHomeView
. - If
isActive
isfalse
, it means the app is not finished showing the Splash screen yet. Hence load the Splash screen content, here ourText
with “Awesome Splash Screen!”. - The magic happens here! We use the
onAppear
callback function which will be called when the view will appear. - The main logic goes here. We basically just change the state of
isActive
totrue
after a delay of2.5
seconds. - We put this in a nice animation block so the state changes will be animated.
When the state property is updated, it also updates the depended views.
Hence our SplashView
will hide its content and show HomeView
now!
Let me show you the output:
That’s all on how to add Splash screen in SwiftUI!
Find the source code for this tutorial on GitHub.
Read more about State properties on Apple Documentation!
If you want to use SwiftUI
and UIKit
together in your existing app then read this article.
And If you want to use UIKit
in your new SwiftUI
app then read this article.
Stay tuned to know more about SwiftUI
!
11 Comments