Display a Web View in your SwiftUI App
As SwiftUI does not provide a native web view, you can use the WebView
view from
the SharedKit module to display web content in your app. It utilized the WKWebView
from WebKit
under the hood.
View Definition
WebView.swift
public struct WebView: UIViewRepresentable {
public init(url: URL) { }
}
It takes the URL of the web content you want to display as a parameter.
Usage Example
import SharedKit
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Text("Apple's Website:")
.font(.title)
WebView(url: URL(string: "https://www.apple.com")!)
.clipShape(RoundedRectangle(cornerRadius: 20, style: .continuous))
}
.padding(20)
.preferredColorScheme(.dark)
}
}
WebView shown in a sheet
We additionally provide a webViewSheet()
view modifier that you can attach to Views and
present by toggling a @Binding
boolean value.
ViewModifier Definition
WebView.swift
extension View {
public func webViewSheet(
_ showSheet: Binding<Bool>,
url: URL,
title: LocalizedStringKey
) -> some View { }
}
showSheet
- Boolean binding indicating whether to show the sheet or not. Directly passed to thesheet()'s
isPresented
parameter.url
- URL of the web page.title
- Title that will be shown on top of the sheet (Inline navigation title).
Usage Example
import SharedKit
import SwiftUI
struct ContentView: View {
@State private var showSheet = false
var body: some View {
VStack {
Button("Show Apple's Website") {
showSheet.toggle()
}
}
.webViewSheet(
$showSheet,
url: URL(string: "https://www.apple.com")!,
title: "Apple's Website"
)
}
}