1
2

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 1 year has passed since last update.

【SwiftUI】WebViewにローディング画面を表示する

Posted at

はじめに

WebViewの読み込み中にローディング画面を表示させます。

WebViewをSwiftUIで使うためのコードは以下の記事のものを使用します。

くるくる 進捗バー
Simulator Screen Recording - iPhone 14 Pro - 2023-04-23 at 21.32.28.gif Simulator Screen Recording - iPhone 14 Pro - 2023-04-23 at 21.34.37.gif

くるくる

import SwiftUI
import Combine
import WebKit

struct ContentView: View {
    @StateObject var viewModel = ViewModel()
    var body: some View {
        WebView(url: URL(string: "https://qiita.com/SNQ-2001")) { webView in
            viewModel.loadingObserver(webView)
        }.overlay {
            if viewModel.isLoading {
                ProgressView().progressViewStyle(.circular)
            }
        }
    }
}


final class ViewModel: ObservableObject {
    @Published var isLoading = false
    
    func loadingObserver(_ webView: WKWebView) {
        webView.publisher(for: \.isLoading)
            .assign(to: &$isLoading)
    }
}

進捗バー

import SwiftUI
import Combine
import WebKit

struct ContentView: View {
    @StateObject var viewModel = ViewModel()
    var body: some View {
        ZStack(alignment: .top) {
            WebView(url: URL(string: "https://qiita.com/SNQ-2001")) { webView in
                viewModel.loadingObserver(webView)
            }
            
            if viewModel.isLoading {
                ProgressView(value: viewModel.estimatedProgress).progressViewStyle(.linear)
            }
        }
    }
}


final class ViewModel: ObservableObject {
    @Published var isLoading = false
    @Published var estimatedProgress = 0.0
    
    func loadingObserver(_ webView: WKWebView) {
        webView.publisher(for: \.isLoading)
            .assign(to: &$isLoading)
        
        webView.publisher(for: \.estimatedProgress)
            .assign(to: &$estimatedProgress)
    }
}

おわり

UIKitでWebViewにローディング画面を表示する記事がいくつかありましたが、SwiftUIでの記事は見つからなかったので記録しておきます。

1
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?