Skip to content

Instantly share code, notes, and snippets.

@hkitago
Last active March 30, 2023 17:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hkitago/8ce025b635c9155b063de1592c8e9bfc to your computer and use it in GitHub Desktop.
Save hkitago/8ce025b635c9155b063de1592c8e9bfc to your computer and use it in GitHub Desktop.
WKWebViewTemplate to display HTML with JavaScript
//
// ContentView.swift
// WKWebViewTemplate
//
// Created by Hiroyuki KITAGO on 2022/01/26.
//
import SwiftUI
import WebKit
struct ContentView: View {
var body: some View {
WebView(htmlFileName: "WKWebViewTemplate")
.edgesIgnoringSafeArea(.all)
}
}
struct WebView : UIViewRepresentable {
let htmlFileName: String
func makeUIView(context: Context) -> WKWebView {
let prefs = WKWebpagePreferences()
prefs.allowsContentJavaScript = true
let config = WKWebViewConfiguration()
config.defaultWebpagePreferences = prefs
let webview = WKWebView(frame: .zero, configuration: config)
/* if you want to hide clock add this to info.plist:
"<key>UIStatusBarHidden</key><true/>
<key>UIViewControllerBasedStatusBarAppearance</key><false/>"
https://stackoverflow.com/questions/56896719/how-to-hide-the-status-bar-in-swiftui */
webview.scrollView.bounces = false
webview.scrollView.showsVerticalScrollIndicator = false
webview.scrollView.showsHorizontalScrollIndicator = false
webview.scrollView.isScrollEnabled = false
if #available(iOS 11.0, *) {
webview.scrollView.contentInsetAdjustmentBehavior = .never
}
return webview
}
func updateUIView(_ uiView: WKWebView, context: Context) {
let htmlPath = Bundle.main.path(forResource: htmlFileName, ofType: "html")
let url = URL(fileURLWithPath: htmlPath!)
let request = URLRequest(url: url)
uiView.load(request)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment