
スプラッシュ画面を構築する。
従来のSwiftであれば、storyboardで設定したりして、スプラッシュ画面を構築する方法があります。
しかしSwiftUIではstoryboardがなく、コードでの実装となります。
そこで、SwiftUIでsplash画面を構築する際のコードについて話そうと思います。
スプラッシュ画面のサンプルコード
import UIKit
import SwiftUI
struct SplashView: View {
// カウントダウンする秒数
@State private var count = 3
// true:カウントダウン中 false:カウントダウン終了
@State private var isCountDown = true
// opacity
@State var opacity: Double = 0
// デフォルトのタグ
@State private var selectedIndex = 0
var body: some View {
VStack {
if !self.isCountDown {
Main()
// 徐々にMainTabBarが表示されるようにしたい。
.opacity(self.opacity)
.onAppear {
withAnimation(.linear(duration: 0.7)) { // linearは線形つまり一定の割合で。
// NOTE: opacityを変更する画面再描画に対してアニメーションを適用する
self.opacity = 1.0
}
}
} else {
Text("Test").font(.system(size: 35, weight: .bold, design: .serif))
Image("sample").resizable().frame(width: 300, height: 300, alignment:.center)
}
}
.onAppear() {
// 1秒ごとに処理を行う
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) {timer in
self.count -= 1 // 残り秒数が減る
if self.count == 0 {
// 残り秒数が0になると終了
timer.invalidate()
self.isCountDown = false
}
}
}
}
}
struct Main: View {
var body: some View {
VStack {
Color.green
.edgesIgnoringSafeArea(.all)
}
}
}