Last active
October 14, 2024 23:19
-
-
Save awunnenb/dc0fcb4d221a0b5c42ea1ff315955458 to your computer and use it in GitHub Desktop.
SwiftUI WKWebView and Back- Forward Buttons
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Youtube Video: https://youtu.be/SBvrvJ93gh4 | |
import SwiftUI | |
import WebKit | |
struct ContentView: View { | |
let webView = WebView(request: URLRequest(url: URL(string: "https://www.google.com")!)) | |
var body: some View { | |
VStack { | |
webView | |
HStack { | |
Button(action: { | |
self.webView.goBack() | |
}){ | |
Image(systemName: "arrowtriangle.left.fill") | |
.font(.title) | |
.foregroundColor(.blue) | |
.padding() | |
} | |
Spacer() | |
Button(action: { | |
self.webView.goHome() | |
}){ | |
Image(systemName: "house.fill") | |
.font(.title) | |
.foregroundColor(.blue) | |
.padding() | |
} | |
Spacer() | |
Button(action: { | |
self.webView.refresh() | |
}){ | |
Image(systemName: "arrow.clockwise.circle.fill") | |
.font(.title) | |
.foregroundColor(.blue) | |
.padding() | |
} | |
Spacer() | |
Button(action: { | |
self.webView.goForward() | |
}){ | |
Image(systemName: "arrowtriangle.right.fill") | |
.font(.title) | |
.foregroundColor(.blue) | |
.padding() | |
} | |
} | |
} | |
} | |
} | |
struct WebView: UIViewRepresentable { | |
let request: URLRequest | |
private var webView: WKWebView? | |
init(request: URLRequest) { | |
self.webView = WKWebView() | |
self.request = request | |
} | |
func makeUIView(context: Context) -> WKWebView { | |
return webView! | |
} | |
func updateUIView(_ uiView: WKWebView, context: Context) { | |
uiView.load(request) | |
} | |
func goBack(){ | |
webView?.goBack() | |
} | |
func goForward(){ | |
webView?.goForward() | |
} | |
func refresh() { | |
webView?.reload() | |
} | |
func goHome() { | |
webView?.load(request) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
check out https://youtu.be/o52XYvwTQU0 to handle external links please