1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

SwiftUIでスプラッシュ画面を実装する

Last updated at Posted at 2022-05-22

実装方法

モディファイアでスプラッシュ画面を実装していきます。

スプラッシュ画面用モディファイア

カスタムビューを表示し、時間が立つと、モディファイア自身でスプラッシュが消えます

SplashModifier.swift
import SwiftUI

private let defaultTimeout: TimeInterval = 2.5

struct SplashModifier<SplashContent: View>: ViewModifier {
    private let timeout: TimeInterval
    private let splashContent: () -> SplashContent
    
    @State private var isActive = true
    
    init(timeout: TimeInterval = defaultTimeout,
         @ViewBuilder splashContent: @escaping () -> SplashContent) {
        self.timeout = timeout
        self.splashContent = splashContent
    }
    
    func body(content: Content) -> some View {
        if isActive {
            splashContent()
                .onAppear {
                    DispatchQueue.main.asyncAfter(deadline: .now() + timeout) {
                        withAnimation {
                            self.isActive = false
                        }
                    }
                }
        } else {
            content
        }
    }
}

extension View {
    func splashView<SplashContent: View>(
        timeout: TimeInterval = defaultTimeout,
        @ViewBuilder splashContent: @escaping () -> SplashContent
    ) -> some View {
        self.modifier(SplashModifier(timeout: timeout, splashContent: splashContent))
    }
}

使い方

アプリのコンテンツビュー(一番トップの親ビュー)にスプラッシュのモディファイアを適応する

ContentView.swift
        // スプラッシュ画面
        .splashView {
            // カスタムビュー
            ZStack {
                   Color.blue
                   Text("スプラッシュ")
                     .fontWeight(.bold)
                     .font(.system(size: 24))
                     .foregroundColor(.white)
                 }
            .edgesIgnoringSafeArea(.all)
        }

参考

GitHub

TDD

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?