0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SwiftUIのWebViewの実装

0
Posted at

##WebViewの実装をOSのバージョンごとに振り分ける。

ContentView.swift 内(表示部)

import SwiftUI
import WebKit

struct ContentView: View {
    @State var isSheet: Bool = False
    var url1 = Bundle.main.url(forResource: "index", withExtension: "html")
    var Body: some View {
        Button(action: {
            isSheet = true
        }) {
            Text("Open View").foregroundColor(.orange).font(.custom("serif-Bold", size:  30)
        }
        .sheet(isPresented: $isSheet) {
            Text("KiraKira Music EQ").foregroundColor(.brown).font(.custom("fantasy-Bold", size: 30)
            VStack {
                Button(action: {
                    isSheet = false
                }) {
                    Text("Close").foregroundColor(.gray).font(.custom("monospace", size: 22)
                }
                Button(action: {
                    if #available(iOS 26, *) {
                      //SwiftUI framework に標準搭載
                        WebView(url: url1)
                    } else {
                        //別にClassシートを用意する
                        loveballad(url: url1)
                    }
                }) {
                    Text("Open The Door").foregroundColor(.cyan).font(.custom("sans-serif", size: 30)
                }
            }
        }
    }
}

この上記の示している事はチートシートを呼び出すため、のシートの開閉を定義するためのブール値をTrue:Falseで定義。
ボタンのアクション内でTrueにし開きさらにシート状のボタンでWebViewを開いています。

次にiOS 17.6, 18用のClassシートを用意
*このシートは現在のXcodeのバージョン27以降には搭載不能となっているようだ。MacOSとiOSのアプリの隔てがなくなったため

loveballad.swift 内

import SwiftUI
import WebKit

class loveballad: UIViewRepresentable {
    var str = String()
    func makeUIView(Context: context) -> UIView {
        let WebView = WKWebView(frame: .infinity)
        let url1 = Bundle.main.url(forResource: str, withExtension: "html")
        WebView.load(url1)
    }
    func updateUIView(Context: context) -> UIView {
        let WebView = WkWebView(frame: .infinity)
        let url1 = Bundle.main.url(forResource: str, withExtensiton: "html")
        WebView.load(url1)
    }
}

こちらは以前に使われていたStoryboardのコードが使えたころにあったiOS専用の読み込み方MacOSではUIKitがSwiftUIで統一されて行っているため、現時点ではUIKitが読み込めない。要注意。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?