WebView
A view that displays some web content.
Declaration
@MainActor @preconcurrency struct WebViewOverview
Present HTML, CSS, and JavaScript content alongside your app’s native views with WebView. Specify web content with a URL when using the init(url:) initializer, or with a WebPage when using the init(_:) initializer, which allows you to fully control the browsing experience. Any updates to the page propagate the information to the view.
WebView provides a complete browsing experience, including the ability to navigate between different webpages using links, forward and back buttons, and more. When a person clicks a link in your content, the view acts like a browser and displays the content at that link. To customize navigation, use a WebPage with your WebView and customize the WebPage.Configuration, or create a new type that conforms to WebPage.NavigationDeciding.
The following example displays two different URLs depending on the state of a toggle, and also prevents back-forward navigation gestures:
import SwiftUI
import WebKit
struct ContentView: View {
@State private var toggle = false
private var url: URL? {
toggle ? URL(string: "https://www.webkit.org") : URL(string: "https://www.swift.org")
}
var body: some View {
WebView(url: url)
.toolbar {
Button(buttonName, systemImage: buttonIcon) {
toggle.toggle()
}
}
.webViewBackForwardNavigationGestures(.disabled)
}
}A WebView is a scrollable view, and behaves similarly to ScrollView. Customize scrolling in a WebView with:
Customize WebView display and interactions with view modifiers, such as:
To further customize and control a web interaction, connect a WebView to a WebPage. The following example demonstrates this by configuring the view’s navigation title to be the webpage’s title, which the system updates automatically because WebPage is an Observable type:
struct ContentView: View {
@State private var page = WebPage()
var body: some View {
NavigationStack {
WebView(page)
.navigationTitle(page.title)
}
}
}