4

I've laid out a couple WKWebViews in SwiftUI (using UIViewRepresentable) for an iPad app.

When I simply click on one those views, it gets focus, and I can use various keyboard shortcuts specific to the website (in the example code below the pages use these DuckDuckGo shortcuts - https://help.duckduckgo.com/duckduckgo-help-pages/features/keyboard-shortcuts/ ), as well as up/down keys to scroll etc.

However, if I just scroll a web view, then it doesn't get focus.

How would I make the page get focus (becomeFirstResponder in UIKit terms) as soon as the web page is scrolled. Additionally, how could I show the focused web view in the UI (for instance, by making the web views border red)?

My code:

import WebKit

struct ContentView: View {
    var body: some View {
        VStack {
            Webview(url: URL(string:"https://duckduckgo.com/?q=stack+overflow&t=h_&ia=web")!)
            Divider()
            Webview(url: URL(string:"https://duckduckgo.com/?q=ipad&t=h_&ia=web")!)
        }
    }
}

struct Webview: UIViewRepresentable {
    let url: URL
    func makeUIView(context: UIViewRepresentableContext<Webview>) -> WKWebView {
        let webview = WKWebView()
        let request = URLRequest(url: self.url, cachePolicy: .returnCacheDataElseLoad)
        webview.load(request)
        return webview
    }
    func updateUIView(_ webview: WKWebView, context: UIViewRepresentableContext<Webview>) {
        let request = URLRequest(url: self.url, cachePolicy: .returnCacheDataElseLoad)
        webview.load(request)
    }
}
cannyboy
  • 24,180
  • 40
  • 146
  • 252
  • When I copy your code nothing shows up. If it's first responder handling that you're looking for maybe https://github.com/Amzd/ResponderChain can help. For the scrolling maybe https://github.com/Amzd/ScrollViewProxy could help but honestly you should probably handle that in your UIViewRepresentable. – Casper Zandbergen May 27 '21 at 17:44

0 Answers0